Back to blog
Mar 19, 2024
3 min read

A guide to API versioning with Swagger in ASP.NET Core

API versioning is a crucial aspect of API development, allowing developers to introduce changes and enhancements to their APIs while ensuring backward compatibility. In this guide, we'll explore how to implement API versioning in an ASP.NET Core application using Swagger for documentation.

Why API Versioning Matters

As your application evolves, so do your APIs. Introducing new features, deprecating old ones, and maintaining backward compatibility are essential aspects of API development. API versioning allows you to manage these changes effectively, ensuring that clients can adapt to new functionality without breaking existing integrations.

Getting Started

Before diving into configuration, let’s ensure we have the necessary packages installed. We’ll use the Asp.Versioning.Http and Asp.Versioning.Mvc.ApiExplorer packages, which provide tools for API versioning in ASP.NET Core.

dotnet install Asp.Versioning.Http
dotnet install Asp.Versioning.Mvc.ApiExplorer

Configuring API Versioning

To configure API versioning in your ASP.NET Core application, you’ll need to add services for API versioning. This involves setting default API versions, enabling version reporting, and specifying how API versions are read.

builder.Services.AddApiVersioning(options =>
{
    options.DefaultApiVersion = new ApiVersion(1);
    options.ReportApiVersions = true;
    options.AssumeDefaultVersionWhenUnspecified = true;
    options.ApiVersionReader = new UrlSegmentApiVersionReader();
}).AddApiExplorer(options =>
{
    options.GroupNameFormat = "'v'VVV";
    options.SubstituteApiVersionInUrl = true;
});

This configuration ensures that API versions are properly identified and that Swagger can generate documentation for each version.

Enabling Versioning in Swagger

Swagger is a powerful tool for API documentation, and integrating it with API versioning enhances the documentation’s clarity and usability. We’ll configure Swagger to generate documentation for each API version.

public class ConfigureSwaggerOptions : IConfigureNamedOptions<SwaggerGenOptions>
{
    private readonly IApiVersionDescriptionProvider _provider;

    public ConfigureSwaggerOptions(IApiVersionDescriptionProvider provider)
    {
        _provider = provider;
    }

    public void Configure(SwaggerGenOptions options)
    {
        foreach (var description in _provider.ApiVersionDescriptions)
        {
            options.SwaggerDoc(
                description.GroupName,
                CreateVersionInfo(description));
        }
    }

    private OpenApiInfo CreateVersionInfo(ApiVersionDescription desc)
    {
        var info = new OpenApiInfo()
        {
            Title = ".NET Core (.NET 8) Web API",
            Version = desc.ApiVersion.ToString()
        };

        if (desc.IsDeprecated)
        {
            info.Description += " This API version has been deprecated. Please use one of the new APIs available from the explorer.";
        }

        return info;
    }
}

Register the Swagger configuration options with the ASP.NET Core dependency injection container to enable Swagger documentation for each API version.

builder.Services.ConfigureOptions<ConfigureSwaggerOptions>();

Finally, set up Swagger UI to visualize and interact with the API documentation. This code snippet enables Swagger UI in the development environment.

if (app.Environment.IsDevelopment())
{
    IReadOnlyList<ApiVersionDescription> descriptions = app.DescribeApiVersions();

    app.UseSwagger();
    app.UseSwaggerUI(options =>
    {
        foreach (var description in descriptions)
        {
            options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json",
                description.GroupName.ToUpperInvariant());
        }
    });
}

Conclusion

API versioning is a fundamental aspect of API development, ensuring that your APIs remain flexible and adaptable over time. By integrating API versioning with Swagger in your ASP.NET Core application, you can provide comprehensive documentation for each API version, empowering developers to consume and integrate with your APIs effectively.

For a practical example, you can refer to the GitHub sample accompanying this guide.

Start versioning your APIs today and streamline your development workflow with Swagger integration!