Introduction
When an API is first released, clients are usually built around specific URLs, field names, data types, and error behaviors. Later, the API may need to add a field, change the meaning of an existing field, or redesign a response. If these changes are made without a compatibility strategy, mobile applications, web clients, integration services, and third-party consumers can break.
API versioning makes it possible to expose different contract versions of the same capability in a controlled way. In this lesson, we will use URL-segment versioning as the primary approach. We will also examine header-based versioning. The goal is not merely to create /api/v1/products and /api/v2/products. The real goal is to define a version policy, protect existing clients, provide a better contract for new clients, and document every version clearly.
Core versioning rules
When should a version change?
A change generally requires a new major API version when it can break an existing client’s JSON parsing, field expectations, or workflow. Removing a field, changing a field’s data type, adding a required response field, or changing the meaning of an endpoint are examples of breaking changes.
Adding a new optional response field may be backward compatible for many JSON clients. However, clients using strict schema validation may still reject the response. Therefore, do not assume that every small change is automatically safe. Client behavior, contract tests, and the release policy must be evaluated together.
URL segments and headers
With URL-segment versioning, the version is visible in the address:
GET /api/v1/products/42 GET /api/v2/products/42
This approach is discoverable, easy to trace in logs, and clearly separated in cache keys. Its main disadvantage is that clients must update the URLs they call.
With header-based versioning, the URL remains unchanged and the version is sent in a request header:
GET /api/products/42 X-Api-Version: 2.0
Header versioning keeps URLs clean, but clients must send the custom header correctly. Some cache, proxy, or observability tools may also expose the version less clearly than they would with a URL. Although multiple versioning methods can be combined, doing so without a clear policy can create unnecessary ambiguity for clients.
Adding API versioning to the project
For a controller-based ASP.NET Core Web API project, the Asp.Versioning.Mvc package and the versioned API Explorer package Asp.Versioning.Mvc.ApiExplorer are commonly used.
dotnet add package Asp.Versioning.Mvc dotnet add package Asp.Versioning.Mvc.ApiExplorer dotnet add package Swashbuckle.AspNetCore
Configure the basic behavior in Program.cs:
using Asp.Versioning; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddApiVersioning(options => { options.DefaultApiVersion = new ApiVersion(1, 0); options.AssumeDefaultVersionWhenUnspecified = false; options.ReportApiVersions = true; options.ApiVersionReader = new UrlSegmentApiVersionReader(); }) .AddMvc() .AddApiExplorer(options => { options.GroupNameFormat = "'v'VVV"; options.SubstituteApiVersionInUrl = true; }); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); app.UseHttpsRedirection(); app.UseSwagger(); app.UseSwaggerUI(options => { options.SwaggerEndpoint("/swagger/v1/swagger.json", "Catalog API v1"); options.SwaggerEndpoint("/swagger/v2/swagger.json", "Catalog API v2"); }); app.MapControllers(); app.Run();
In this configuration, requests without a version are not silently routed to v1. This forces clients to state which contract they use. When ReportApiVersions is enabled, the server can also communicate supported and deprecated versions through response headers.
In production applications, dynamically generating Swagger documents is preferable. New versions can then be added without manually rewriting the Swagger UI configuration. Version groups created by API Explorer can be obtained through IApiVersionDescriptionProvider, and an OpenAPI document can be registered for each group.
Managing v1 and v2 controllers together
Keeping different versions of the same resource in separate controllers makes contract differences visible and easier to maintain. In the following example, the v1 response has a smaller contract:
using Asp.Versioning; using Microsoft.AspNetCore.Mvc; [ApiController] [ApiVersion("1.0")] [Route("api/v{version:apiVersion}/products")] public sealed class ProductsV1Controller : ControllerBase { [HttpGet("{id:int}")] public ActionResult<ProductResponseV1> Get(int id) { var product = new ProductResponseV1( id, "Mechanical Keyboard", 89.90m); return Ok(product); } } public sealed record ProductResponseV1( int Id, string Name, decimal Price);
In v2, new clients can receive currency and category information:
[ApiController] [ApiVersion("2.0")] [Route("api/v{version:apiVersion}/products")] public sealed class ProductsV2Controller : ControllerBase { [HttpGet("{id:int}")] public ActionResult<ProductResponseV2> Get(int id) { var product = new ProductResponseV2( id, "Mechanical Keyboard", new MoneyResponse(89.90m, "USD"), new CategoryResponse(7, "Accessories")); return Ok(product); } } public sealed record ProductResponseV2( int Id, string Name, MoneyResponse Price, CategoryResponse Category); public sealed record MoneyResponse(decimal Amount, string Currency); public sealed record CategoryResponse(int Id, string Name);
The two controllers do not need to duplicate business logic. Shared rules should remain in the application or service layer. Controllers should handle version routing, select the version-specific DTO, and create the HTTP response.
Evolving contracts without breaking clients
Clients using v1 should not be forced to receive the v2 response. For that reason, creating a new DTO is usually safer than modifying the existing DTO in place. Use the following rules as a practical checklist:
- Do not remove v1 response fields or change their meaning.
- Do not change a field’s data type; introduce a new field or a new version instead.
- When possible, add new response fields as optional and give them an unambiguous meaning.
- When adding enum values, verify that clients can handle unknown values.
- Avoid changing the error response format unnecessarily across versions.
- If endpoint behavior changes, do not overwrite the old behavior merely to preserve the URL.
The same principle applies to request DTOs. If v1 accepts price as a decimal and v2 changes it to an object containing currency, that may be a breaking change. The conversion belongs in the v2 request contract while the existing v1 contract remains intact.
Header-based versioning
If you prefer a request header instead of a URL segment, replace the version reader configuration:
builder.Services.AddApiVersioning(options => { options.DefaultApiVersion = new ApiVersion(1, 0); options.AssumeDefaultVersionWhenUnspecified = false; options.ReportApiVersions = true; options.ApiVersionReader = new HeaderApiVersionReader("X-Api-Version"); }) .AddMvc() .AddApiExplorer(options => { options.GroupNameFormat = "'v'VVV"; });
The same route can then select a controller according to the header value:
GET /api/products/42 X-Api-Version: 1.0
or:
GET /api/products/42 X-Api-Version: 2.0
Because the route template no longer contains {version:apiVersion}, sending the correct header becomes critical. Missing or unsupported versions should produce a consistent error response and be clearly documented for consumers.
Exposing versions through Swagger/OpenAPI
If several versions are merged into one Swagger document, endpoints and response schemas can become confusing. A separate OpenAPI document for each API version is clearer. The Swagger UI should allow users to select “Catalog API v1” and “Catalog API v2” independently.
When URL-segment versioning is used, the API Explorer option SubstituteApiVersionInUrl is important. It helps the Swagger output display concrete paths such as v1 and v2 instead of the abstract v{version} template. As a result, the “Try it out” operation calls the correct endpoint.
Swagger documentation should contain more than a version number. Each version should explain its support status, deprecation date, migration guidance, and breaking-change notes. If an old version will be retired, response headers, portal announcements, and direct client communication should be planned together.
Common mistakes
1. Only adding the version to the controller name
Naming a class ProductsV2Controller is not enough for routing. The controller also needs [ApiVersion("2.0")] metadata and a route that matches the chosen versioning strategy.
2. Modifying the v1 DTO for v2
This can break old clients because of unexpected field types or newly required fields. Use explicit DTOs for each contract version.
3. Applying a default version silently
When AssumeDefaultVersionWhenUnspecified is enabled, clients that omit a version may be attached to a version unexpectedly. If this is necessary during a migration, document the decision and monitor it with telemetry.
4. Showing only v1 in Swagger
Even when the endpoints work, consumers cannot discover v2 if API Explorer and Swagger are not updated. Add a document, examples, and response schemas for every new version.
5. Coupling versioning to the database model
The API contract and the persistence model are not the same thing. Different DTOs can be produced from the same entity. Tying versioning directly to table or entity names adds unnecessary complexity.
Practice exercise
- Add v1 API metadata and a URL-segment route to the existing product endpoint.
- Create a ProductsV2Controller and add a Currency field to its response.
- Generate separate Swagger documents for v1 and v2.
- Compare GET /api/v1/products/1 with GET /api/v2/products/1.
- Verify with an integration test that the v1 response is unaffected by the v2 change.
- Inspect the supported-version response headers and write a deprecation plan for an unused version.
Conclusion
API versioning is much more than adding a number to a URL. Version strategy, breaking-change analysis, DTO separation, client migration, error behavior, and Swagger documentation must be designed together. URL segments provide visibility and traceability, while headers can keep URLs simpler.
In a professional API, existing clients do not encounter unexpected contract changes, and new clients use a clearly defined, documented, and tested version. In the next lesson, we will protect this API with JWT-based authentication and authorization.
Sources
- https://github.com/dotnet/aspnet-api-versioning
- https://github.com/dotnet/aspnet-api-versioning/wiki/How-to-Version-Your-Service
- https://github.com/dotnet/aspnet-api-versioning/wiki/API-Explorer-Options
- https://github.com/dotnet/aspnet-api-versioning/wiki/API-Documentation
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/openapi/overview