Introduction
In a situation where we need to modify our API’s structure or functionality while ensuring that existing API clients remain unaffected, the solution is versioning.
We can designate our current APIs as the older version and introduce all intended changes in the next (or latest) version. This approach resolves two key issues:
- Backward compatibility is maintained as the current APIs continue to coexist. This ensures that our clients won’t encounter any problems.
- We gain the ability to offer optional functionalities to clients through different versions. Clients can choose a particular version to access new or improved features without disrupting their existing setup.
Things to keep in mind while Versioning
When adding versioning to our APIs, we need to check three things:
- Ensure the system can understand the requested version.
- Confirm that requests are directed to the appropriate versioned endpoints, like sending v2 requests to v2 endpoints.
- Decide on the best method to include version information in the requests.
In ASP.NET Core, versioning APIs is made easy thanks to the support provided by the API Versioning library for ASP.NET Core.
We implement the API versioning mechanism in 3 steps.
Install Nuget Package
dotnet add package Microsoft.AspNetCore.Mvc.Versioning
Register API Versioning service
Include the API Versioning service in the IServiceCollection to enable it to detect and direct requests according to their version.
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IHeroesRepository, HeroesRepository>();
services.AddControllers();
services.AddApiVersioning(setup =>
{
setup.DefaultApiVersion = new ApiVersion(1, 0);
setup.AssumeDefaultVersionWhenUnspecified = true;
setup.ReportApiVersions = true;
});
}
Modify API Controller
We label the API Controller with the version numbers it uses when a request for that specific version is made.
namespace Heroes.Api.Controllers.V2
{
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[Route("api/[controller]")] // for backward compatibility
public class HeroesController : ControllerBase
{
// heroes CRUD operations
}
}
The [ApiVersion] indicates which version the controller corresponds to, using the version specified in the route as ‘v{version:apiVersion.’ This includes the version number in the route when matching requests.
For example, both ‘/api/v1.0/heroes/1’ and ‘/api/v1/heroes/1’ match this controller. API versions can have major and minor components. Sometimes, the minor part is omitted, leaving it up to the developers to specify.
When we use both [Route(“api/v{version:apiVersion}/[controller]”)] and [Route(“api/[controller]”)] on a controller, we ensure support for requests from older route templates. This is important for compatibility with older route paths, ensuring both ‘/api/v1/heroes/1’ and ‘/api/heroes/1’ are handled by the mentioned controller.
To introduce a new version of the same controller with additional features or changes, we create a new controller (or extend the current one if no changes are needed) and assign it the next version number.
How do we pass the Version Information?
There are various approaches to pass version information to the API when requesting data.
via URL Segment
The default method is the URL Segment approach, where we put the version info in the URL path. The ASP.NET Core ApiVersion service checks the path for this version and decides which controller to use for the request.
Big API providers like Google and Facebook also use URL Segments to pick the API version. To set this explicitly, we choose it as the ApiVersionReader like this:
services.AddApiVersioning(setup =>
setup.ApiVersionReader = new UrlSegmentApiVersionReader());
via Query
In this method, the version is added to the URL as a query parameter. The benefit is that the URL remains neat, and we can change the version by adjusting the query parameter. However, the downside is that if we modify the version number, we must update it in all URLs with the query parameters. To use query parameter-based versioning, we set up the QueryStringApiVersionReader in the AddApiVersioning() function.
By default, the version is sent using the “api-version” query parameter, but we can change it by specifying a different parameter name in the QueryStringApiVersionReader’s constructor. For example, AWS APIs use this method to specify the version of the service to invoke through the query parameter.
// /api/heroes/?api-version=2.0 - default
services.AddApiVersioning(
options => options.ApiVersionReader = new QueryStringApiVersionReader());
// /api/heroes/?v=2.0
services.AddApiVersioning(
options => options.ApiVersionReader = new QueryStringApiVersionReader("v"));
via Header
The third method uses request headers to convey version information, keeping the URL clean and constant. The version to map is decided based on the request header. To enable this, we use the HeaderApiVersionReader as the ApiVersionReader to look for version details in the headers.
services.AddApiVersioning(
options => options.ApiVersionReader = new HeaderApiVersionReader("api-version"));
via Content Type
The fourth method uses expanded media types in request headers to communicate version details. To do this, we use ApiVersionReader with an instance of MediaTypeApiVersionReader(). By default, the version is sent as “v={versionNumber},” but we can change this by specifying the desired key in the constructor, similar to how we customize QueryStringApiVersionReader().
// Content-Type: application/json;v=2.0 - default
services.AddApiVersioning(
options => options.ApiVersionReader = new MediaTypeApiVersionReader());
// Content-Type: application/json;version=2.0
services.AddApiVersioning(
options => options.ApiVersionReader = new MediaTypeApiVersionReader("version"));
Reading from More than one Source
Sometimes, we might want to get version information from different sources instead of sticking to one method all the time. In those situations, we can use multiple ApiVersionReader instances, as shown below.
services.AddApiVersioning(setup =>
{
setup.ApiVersionReader = ApiVersionReader.Combine(
new UrlSegmentApiVersionReader(),
new HeaderApiVersionReader("api-version"),
new QueryStringApiVersionReader("api-version"),
new MediaTypeApiVersionReader("version"));
});
Summary
API versioning is used when you need to modify your API’s structure or functionality while ensuring existing clients are not affected. It allows you to maintain backward compatibility and offer optional features through different versions. Some key considerations you may need to make — Ensure the system can understand the requested version. Confirm that requests are routed to the correct versioned endpoints. Decide how to include version information in requests.
ASP.NET Core provides support for API versioning through the API Versioning library.
You will follow these implementation steps.
- Install the required NuGet package.
- Register the API Versioning service in the IServiceCollection to enable version detection and routing.
- Label your API Controllers with version numbers to specify which version they correspond to.
Version information can be passed in various ways — URL Segment, Query Parameters, Headers, and Content Type. In some cases, you may need to retrieve version information from multiple sources. You can achieve this by using multiple instances of ApiVersionReader.