Swagger / OpenAPI

Swagger (now known as OpenAPI) is a framework for API documentation and specification. It allows you to describe your RESTful API in a machine-readable format, providing a way to generate interactive documentation, client SDKs, and server stubs.

Overview of Swagger / OpenAPI

OpenAPI Specification (OAS) is a standard for defining RESTful APIs. It provides a way to describe the endpoints, request/response formats, parameters, authentication methods, and more.

Swagger tools are used to generate interactive documentation and client libraries based on the OpenAPI specification.


Setting Up Swagger in ASP.NET Core

1. Install Swagger NuGet Packages

dotnet add package Swashbuckle.AspNetCore

2. Configure Swagger in Program.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
 
    // Register Swagger services
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    });
}
 
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ... other middleware ...
 
    // Use Swagger
    app.UseSwagger();
 
    // Use Swagger UI
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
        c.RoutePrefix = string.Empty; // Set Swagger UI at the app's root (optional)
    });
 
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

3. XML Comments for Enhanced Documentation

Enable XML documentation in your project file (.csproj):

<PropertyGroup>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
    <NoWarn>1591</NoWarn> <!-- Suppress missing XML comment warnings -->
</PropertyGroup>

Update Swagger configuration:

c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "MyApi.xml"));

4. Testing the API Documentation

Run your application and navigate to the Swagger UI (usually at /swagger or the root if configured) to see interactive API documentation.


Content Negotiation

Content negotiation is a mechanism in HTTP that allows clients and servers to agree on the format of the response data.

How Content Negotiation Works

  1. Client Request: The client sends an HTTP request with the Accept header specifying the desired media type (e.g., application/json, application/xml).
  2. Server Response: The server uses formatters to serialize the response data into the specified format.

Configuring Formatters in ASP.NET Core

JSON Formatter with System.Text.Json:

services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNamingPolicy = null; // Disable camel casing
    });

JSON Formatter with Newtonsoft.Json:

dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson
services.AddControllers()
    .AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    });

XML Formatter:

services.AddControllers()
    .AddXmlSerializerFormatters(); // Add XML formatter

Custom Formatters:

public class CustomXmlOutputFormatter : TextOutputFormatter
{
    public CustomXmlOutputFormatter()
    {
        SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/custom-xml"));
    }
 
    public override bool CanWriteResult(OutputFormatterCanWriteContext context)
    {
        return context.ContentType.Equals(MediaTypeHeaderValue.Parse("application/custom-xml"));
    }
 
    public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
    {
        // Implement custom XML serialization logic here
    }
}

Register the custom formatter:

services.AddControllers(options =>
{
    options.OutputFormatters.Add(new CustomXmlOutputFormatter());
});

Testing Content Negotiation

curl -H "Accept: application/json" https://localhost:5001/api/products
curl -H "Accept: application/xml" https://localhost:5001/api/products

API Versioning

API versioning allows you to introduce new features or changes in your API without breaking existing clients.

Implementing API Versioning with Asp.Versioning.Mvc

1. Install the Package:

dotnet add package Asp.Versioning.Mvc

2. Configure API Versioning in Program.cs:

services.AddApiVersioning(options =>
{
    options.ReportApiVersions = true;
    options.AssumeDefaultVersionWhenUnspecified = true;
    options.DefaultApiVersion = new ApiVersion(1, 0);
    options.ApiVersionReader = new HeaderApiVersionReader("api-version");
});

3. Define API Versions in Controllers:

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    [ApiVersion("1.0")]
    public IActionResult GetV1()
    {
        return Ok("API Version 1.0");
    }
 
    [HttpGet]
    [ApiVersion("2.0")]
    [Route("v2")]
    public IActionResult GetV2()
    {
        return Ok("API Version 2.0");
    }
}

4. URL Versioning:

[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        return Ok("API Versioned");
    }
}

5. Query String Versioning:

services.AddApiVersioning(options =>
{
    options.ApiVersionReader = new QueryStringApiVersionReader("api-version");
});

Key Points to Remember

  1. Content Negotiation: Determines the format of the response based on the client’s Accept header.
  2. Built-in Formatters: ASP.NET Core provides JSON and XML formatters out of the box.
  3. API Versioning: Allows multiple versions of an API to coexist and ensures backward compatibility.
  4. New Package: Use Asp.Versioning.Mvc instead of the deprecated Microsoft.AspNetCore.Mvc.Versioning.
  5. Configuration: Set up API versioning in Program.cs using AddApiVersioning.
  6. Testing: Validate versioning using tools like Postman or curl.