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.AspNetCore2. 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
- Client Request: The client sends an HTTP request with the
Acceptheader specifying the desired media type (e.g.,application/json,application/xml). - 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.NewtonsoftJsonservices.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});XML Formatter:
services.AddControllers()
.AddXmlSerializerFormatters(); // Add XML formatterCustom 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/productsAPI 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.Mvc2. 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
- Content Negotiation: Determines the format of the response based on the client’s
Acceptheader. - Built-in Formatters: ASP.NET Core provides JSON and XML formatters out of the box.
- API Versioning: Allows multiple versions of an API to coexist and ensures backward compatibility.
- New Package: Use
Asp.Versioning.Mvcinstead of the deprecatedMicrosoft.AspNetCore.Mvc.Versioning. - Configuration: Set up API versioning in
Program.csusingAddApiVersioning. - Testing: Validate versioning using tools like Postman or curl.