DEV Community

🌵azzd🌵
🌵azzd🌵

Posted on

ASP.NET Core Web API with Swagger API Versioning for dotnet 8

Abstract

In this article, we will explore how to implement URL-based API version control in ASP.NET Core Web API and integrate version control with Swagger using the Asp.Versioning.Mvc and Asp.Versioning.Mvc.ApiExplorer NuGet packages. This versioning mechanism not only helps maintain old versions of the API while introducing changes in new versions but also provides clear documentation and a testing interface for different versions of the API through Swagger UI.

Introduction

As web applications evolve and change, API versioning becomes an essential consideration. It allows developers to introduce incompatible API changes without breaking existing client implementations. Implementing version control in ASP.NET Core Web API can keep your app flexible and scalable.

How to Implement URL-Based API Version Control in ASP.NET Core Web API

URI version control is achieved by embedding the version information directly into the URL, making it a commonly used scheme in many API designs due to its intuitiveness and ease of understanding.

Step 1: Install the Required NuGet Packages

To implement URL-based API version control, the first step is to install the Asp.Versioning.Mvc NuGet package. Note that the Microsoft.AspNetCore.Mvc.Versioning package used before dotnet 5 has been deprecated.

dotnet add package Asp.Versioning.Mvc --version 8.0.0
Enter fullscreen mode Exit fullscreen mode

Step 2: Configure Version Control

Configure version control in Program.cs or Startup.cs to enable API version reporting. This allows clients to know which versions of the API the server supports.

builder.Services.AddApiVersioning(options =>
{
    options.ReportApiVersions = true;
});
Enter fullscreen mode Exit fullscreen mode

Step 3: Add Version Information to Controllers

Specify API version information on the controller to ensure the API access path includes the version number.

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // ...
}
Enter fullscreen mode Exit fullscreen mode

This way, clients can access a specific version of the API through URLs like api/v1/values.

Integrating Version Control into Swagger

Integrating API version control into Swagger not only provides interface documentation but also allows testing different versions of the API through Swagger UI.

Step 1: Install the Swagger Integration Package

First, install the Swagger package that integrates with API version control.

dotnet add package Asp.Versioning.Mvc.ApiExplorer --version 8.0.0
Enter fullscreen mode Exit fullscreen mode

Step 2: Configure Swagger to Support API Version Control

Configure API version control and Swagger integration in Program.cs to ensure there is a Swagger document for each version of the API.

builder.Services.AddApiVersioning(
    options =>
    {
        options.ReportApiVersions = true;
    })
.AddApiExplorer(
    options =>
    {
        options.GroupNameFormat = "'v'VVV";
        options.SubstituteApiVersionInUrl = true;
    });
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure Swagger UI to Display Different Versions of the API

Through the ConfigureSwaggerOptions class and SwaggerGenOptions, add a Swagger document for each discovered API version and display these versions in Swagger UI.

public class ConfigureSwaggerOptions : IConfigureOptions<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, CreateInfoForApiVersion(description));
        }
    }

    private OpenApiInfo CreateInfoForApiVersion(ApiVersionDescription description)
    {
        var info = new OpenApiInfo
        {
            Title = "API Title",
            Version = description.ApiVersion.ToString(),
            Description = "API Description. This API version has been deprecated."
        };

        return info;
    }
}

builder.Services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>();
Enter fullscreen mode Exit fullscreen mode

Finally, enable Swagger in Startup.cs and configure Swagger UI to display endpoints for different versions of the API.

app.UseSwagger();
app.UseSwaggerUI(
    options =>
    {
        var descriptions = app.DescribeApiVersions();

        foreach (var description in descriptions)
        {
            options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
        }
    });
Enter fullscreen mode Exit fullscreen mode

Conclusion

Through the above steps, we not only implemented URL-based API version control, but also successfully integrated it into Swagger, thereby providing clear, easy-to-access documentation and testing interfaces for different versions of the API. This approach ensures the long-term maintainability and backward compatibility of the API, while also improving the developer and end-user experience.

Top comments (0)