API versioning is crucial for maintaining and evolving APIs while ensuring backward compatibility for existing clients. In this guide, we will explore how to set up API versioning in ASP.NET Core locally using URL-based, query-string, and header-based versioning methods. We will also leverage Microsoft.AspNetCore.Mvc.Versioning
to efficiently manage different versions and discuss best practices for handling backward compatibility.
Why API Versioning?
API versioning helps to:
- Provide seamless API evolution without breaking existing client applications.
- Allow multiple API versions to coexist in a single service.
- Ensure smooth transitions for consumers when new features are introduced.
- Maintain backward compatibility while implementing changes.
Installing Required NuGet Package
To implement API versioning in ASP.NET Core, install the Microsoft.AspNetCore.Mvc.Versioning
package via NuGet:
Install-Package Microsoft.AspNetCore.Mvc.Versioning
Alternatively, you can add it using the .NET CLI:
dotnet add package Microsoft.AspNetCore.Mvc.Versioning
Configuring API Versioning
In ASP.NET Core, API versioning can be implemented using various strategies:
- URL-based versioning (e.g.,
/api/v1/controller
) - Query string-based versioning (e.g.,
/api/controller?api-version=1.0
) - Header-based versioning (e.g., passing
api-version
in headers)
1. Configuring API Versioning in Startup
Modify Program.cs
to configure API versioning:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Versioning;
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
services.AddControllers();
// Configure API Versioning
services.AddApiVersioning(options =>
{
options.ReportApiVersions = true;
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
options.ApiVersionReader = ApiVersionReader.Combine(
new UrlSegmentApiVersionReader(),
new QueryStringApiVersionReader("api-version"),
new HeaderApiVersionReader("X-Api-Version")
);
});
services.AddVersionedApiExplorer(options =>
{
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = true;
});
var app = builder.Build();
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
app.Run();
2. Implementing URL-Based Versioning
With URL versioning, the API version is specified as a part of the URL:
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("1.0")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetProducts()
{
return Ok(new { Message = "Products from API v1" });
}
}
3. Implementing Query String-Based Versioning
With query-string versioning, clients pass the version as a query parameter:
[ApiController]
[Route("api/[controller]")]
[ApiVersion("1.0")]
public class OrdersController : ControllerBase
{
[HttpGet]
public IActionResult GetOrders()
{
return Ok(new { Message = "Orders from API v1" });
}
}
Clients can request the version using:
GET /api/orders?api-version=1.0
4. Implementing Header-Based Versioning
With header versioning, clients pass the version in request headers:
[ApiController]
[Route("api/[controller]")]
[ApiVersion("1.0")]
public class CustomersController : ControllerBase
{
[HttpGet]
public IActionResult GetCustomers()
{
return Ok(new { Message = "Customers from API v1" });
}
}
Clients need to include the version in the request headers:
GET /api/customers
X-Api-Version: 1.0
Best Practices for API Versioning and Backward Compatibility
- Default API Version: Define a default version to serve requests that do not specify a version explicitly.
- Deprecation Strategy: Mark old API versions as deprecated using
[ApiVersion("1.0", Deprecated = true)]
. - Versioning Policy: Adopt a clear versioning policy (e.g., semantic versioning).
- Testing: Ensure comprehensive testing of new versions to avoid regressions.
- Client Communication: Notify clients before deprecating older versions.
- API Documentation: Use tools like Swagger to document API versions.
Conclusion
API versioning in ASP.NET Core ensures flexibility and backward compatibility while introducing new changes. By leveraging Microsoft.AspNetCore.Mvc.Versioning
, developers can efficiently implement versioning strategies like URL-based, query-string, and header-based approaches. Adopting best practices helps maintain seamless API evolution while minimizing disruptions for clients.
By following these strategies, you can ensure that your API remains scalable, maintainable, and user-friendly over time.