Skip to content

10.6 — API Versioning Strategies

← Roadmap · Section: 10. Web API Design and REST Prev: 10.5 Content negotiation and JSON · Next: 10.7 Pagination and filtering

Markers: ⭐ 💻 · Confidence: 🔴 · Last reviewed: —


TL;DR

API versioning is how you change an API without breaking the clients already using it.

  • Four places to put the version: URL path, query string, custom header, media type.
  • URL path (/api/v1/orders) wins in practice — visible, cacheable, trivially testable in a browser.
  • The best version is the one you never have to add. Most changes can be made additively; version only for genuinely breaking ones.

Definitions

Term What it is What it means
Breaking change a concept A change that makes an existing client stop working.
Additive change a concept Adding something optional. Existing clients are unaffected.
URL path versioning a strategy /api/v1/orders. The version is in the path.
Query string versioning a strategy /api/orders?api-version=1.0.
Header versioning a strategy X-Api-Version: 1.0. Invisible in the URL.
Media type versioning a strategy Accept: application/json;v=1.0. Purest, least practical.
Asp.Versioning.Mvc a NuGet package The versioning library. Formerly Microsoft.AspNetCore.Mvc.Versioning.
[ApiVersion] an attribute Declares which version a controller or action serves.
[MapToApiVersion] an attribute Maps one action to one specific version.
ApiVersionReader a class Decides where the version is read from.
Deprecation a lifecycle stage Still working, but scheduled for removal.
Sunset a lifecycle stage Switched off.

The concept

The problem

You ship an API. Mobile apps, partner integrations and internal services start calling it. Then a requirement arrives that needs the response to change shape.

You cannot just change it. A mobile app in the wild is not something you can redeploy — users update when they feel like it, and some never do. Change the contract and those clients break.

Versioning is how both shapes coexist while clients migrate.

The more important point: most changes do not need a version

Before choosing a strategy, know which changes actually break clients:

Change Breaking?
Adding an optional request field ✅ Safe
Adding a response field ✅ Safe (if clients ignore unknowns — most JSON clients do)
Adding a new endpoint ✅ Safe
Making an optional field required ❌ Breaking
Removing or renaming a field ❌ Breaking
Changing a field's type ❌ Breaking
Changing a status code for the same condition ❌ Breaking
Tightening validation ❌ Breaking
Changing default sort order or pagination size ⚠️ Breaking in practice

⚠️ That last row is the one people miss. Nothing in the contract changed, but a client that took the first page and assumed an order now shows different data. Behavioural changes break clients just as effectively as schema changes.

The strongest interview answer starts here: design additively, and version only when the change genuinely cannot be additive. Every version you add is a code path you maintain and test forever.

The analogy

A version is a forwarding address. Useful when you genuinely move, expensive to maintain, and better avoided by not moving. Nobody admires a company that changes address every quarter.


How it works

The four strategies

1. URL path — /api/v1/orders

✅ Visible, obvious, browser-testable, caches cleanly, easy to route
⚠️ Not REST-pure — the same resource has two URLs
⚠️ Version leaks into every link and every piece of client code

2. Query string — /api/orders?api-version=1.0

✅ The URL stays clean; can default to latest when omitted
⚠️ Easy to forget; caches key on the full URL, so behaviour varies

3. Header — X-Api-Version: 1.0

✅ The URL identifies the resource only — REST-pure
⚠️ Invisible. Cannot test in a browser address bar
⚠️ Caches ignore it unless you set Vary, so one version can be served from another's cache

4. Media type — Accept: application/vnd.company.order.v1+json

✅ The purest — versioning the representation, which is what actually changed
⚠️ Awkward to write, poorly supported by tools, confusing to most clients

What to actually pick

URL path versioning, for a public or partner-facing API. It is the least elegant and the most usable, and the tooling story — Swagger, generated clients, curl in a bug report — is far better.

Header versioning is defensible for internal service-to-service APIs where clients are code you control and nobody tests by pasting a URL into a browser.

⚠️ The cache trap with header versioning is worth stating explicitly. A CDN or proxy keys on the URL. Two versions share a URL, so v2 can be served a cached v1 response. Vary: X-Api-Version fixes it, and forgetting it produces one of the more baffling production bugs there is (19.5).

How it actually works — the library

dotnet add package Asp.Versioning.Mvc
dotnet add package Asp.Versioning.Mvc.ApiExplorer   # for Swagger integration

⚠️ The package was renamed. Microsoft.AspNetCore.Mvc.Versioning is the old name and is no longer updated; Asp.Versioning.* is current. Following an old tutorial gets you a dead package.

builder.Services.AddApiVersioning(options =>
{
    options.DefaultApiVersion = new ApiVersion(1, 0);

    // ⚠️ Without this, a request with no version gets 400 rather than the default
    options.AssumeDefaultVersionWhenUnspecified = true;

    // Advertises api-supported-versions / api-deprecated-versions response headers
    options.ReportApiVersions = true;

    options.ApiVersionReader = ApiVersionReader.Combine(
        new UrlSegmentApiVersionReader(),
        new HeaderApiVersionReader("X-Api-Version"),
        new QueryStringApiVersionReader("api-version"));
})
.AddApiExplorer(options =>
{
    options.GroupNameFormat = "'v'VVV";          // v1, v1.1, v2
    options.SubstituteApiVersionInUrl = true;    // fills {version} in Swagger's URLs
});

⚠️ AssumeDefaultVersionWhenUnspecified is a one-way door. Turn it on and unversioned clients work — which means the "default" version can never change without breaking them. Turn it off and you get honest 400s but must version every client from day one. Decide deliberately; retrofitting either direction hurts.

The deeper detail — deprecation

Adding a version is easy. Removing one is the hard part, and it is where the good answers separate from the recited ones.

[ApiVersion("1.0", Deprecated = true)]   // → api-deprecated-versions header
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/orders")]
public sealed class OrdersController : ControllerBase { }

A workable lifecycle:

  1. Announce — release notes, email, dashboard banner.
  2. Mark deprecated — Deprecated = true, plus a Sunset header with the removal date (RFC 8594).
  3. Measure — log the version on every request. You cannot retire what you cannot count.
  4. Contact the remaining callers — by API key or client ID.
  5. Brownout — return 410 for an hour, then restore. Nothing surfaces a forgotten integration like a brief, announced outage.
  6. Sunset.

⚠️ Step 3 is the one people skip, and it is the one that makes the rest possible. Without per-version usage metrics, retirement is a guess, and the answer is always "leave it running".

// A filter that records which version each caller uses
public sealed class ApiVersionMetricsFilter : IActionFilter
{
    private readonly ILogger<ApiVersionMetricsFilter> _log;
    public ApiVersionMetricsFilter(ILogger<ApiVersionMetricsFilter> log) => _log = log;

    public void OnActionExecuting(ActionExecutingContext context)
    {
        var version = context.HttpContext.GetRequestedApiVersion()?.ToString() ?? "unspecified";
        var client  = context.HttpContext.User.FindFirst("client_id")?.Value ?? "anonymous";

        // Structured properties — so you can group by version AND by client later
        _log.LogInformation("ApiVersionUsed {Version} {ClientId} {Path}",
            version, client, context.HttpContext.Request.Path);
    }

    public void OnActionExecuted(ActionExecutedContext context) { }
}

⚠️ Versioning is not a substitute for versioning your data. A v1 and v2 endpoint over the same database still share a schema. If v2 needs a column v1 cannot supply, the mapping problem is in the data layer, not the controller — and that is usually the part that makes a version genuinely expensive.


Code

Two versions side by side:

[ApiController]
[ApiVersion("1.0", Deprecated = true)]
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/orders")]
public sealed class OrdersController : ControllerBase
{
    private readonly IOrderService _orders;
    public OrdersController(IOrderService orders) => _orders = orders;

    // Serves BOTH versions — nothing about it changed between them
    [HttpGet("{id:int}")]
    public async Task<ActionResult<OrderDto>> Get(int id, CancellationToken ct)
    {
        var order = await _orders.FindAsync(id, ct);
        return order is null ? NotFound() : Ok(order);
    }

    // v1 only: a flat list, no pagination. Kept working, not improved.
    [HttpGet]
    [MapToApiVersion("1.0")]
    public async Task<ActionResult<IReadOnlyList<OrderDtoV1>>> ListV1(CancellationToken ct)
    {
        var orders = await _orders.GetAllAsync(ct);
        return Ok(orders.Select(OrderDtoV1.From).ToList());
    }

    // v2: paginated envelope. THIS is the breaking change — the response went from
    // an array to an object, so any client indexing response[0] would break.
    [HttpGet]
    [MapToApiVersion("2.0")]
    public async Task<ActionResult<PagedResult<OrderDtoV2>>> ListV2(
        [FromQuery] PageRequest page, CancellationToken ct)
        => Ok(await _orders.GetPagedAsync(page, ct));
}

Keeping the versions in separate namespaces once they diverge:

namespace Api.V1.Controllers;

[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/orders")]
public sealed class OrdersController : ControllerBase { /* frozen */ }
namespace Api.V2.Controllers;

[ApiController]
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/orders")]
public sealed class OrdersController : ControllerBase { /* active development */ }

⚠️ Two controllers with the same class name in different namespaces is legal, and it is the cleaner arrangement once the two versions genuinely diverge — [MapToApiVersion] on every action gets unreadable past two versions. The trade is duplicated code; the honest framing is that a frozen v1 should be duplicated rather than sharing a base class with v2 that keeps changing underneath it.

Swagger with one document per version:

app.UseSwaggerUI(options =>
{
    var provider = app.Services.GetRequiredService<IApiVersionDescriptionProvider>();

    foreach (var description in provider.ApiVersionDescriptions.Reverse())  // newest first
    {
        options.SwaggerEndpoint(
            $"/swagger/{description.GroupName}/swagger.json",
            description.GroupName.ToUpperInvariant()
                + (description.IsDeprecated ? " (deprecated)" : ""));
    }
});

Interview questions

Q: What are the API versioning strategies and which would you choose?

Four: the URL path, a query string parameter, a custom header, or the media type in Accept. In practice I would use the URL path for anything public or partner-facing — it is visible, it caches correctly, you can test it in a browser, and the tooling for Swagger and generated clients is much better. Header versioning is purer, because the URL then identifies only the resource, and it is defensible internally, but it is invisible and it has a real cache trap: proxies key on the URL, so without Vary: X-Api-Version a v2 request can be served a cached v1 response.

Q: What counts as a breaking change?

Removing or renaming a field, changing a field's type, making an optional field required, tightening validation, and changing which status code you return for a given condition. Adding optional request fields, response fields and new endpoints is safe, assuming clients ignore properties they do not recognise, which most JSON clients do. The one people forget is behavioural: changing a default sort order or default page size breaks a client that took the first page and assumed a particular order, even though nothing in the schema moved.

Q: How do you retire an old version?

The mechanics are easy — mark it deprecated so the library emits the api-deprecated-versions header, and send a Sunset header with the removal date. The part that actually determines whether it happens is measurement: log the requested version and the client ID on every request, so you can see who is still on v1 rather than guessing. Then contact the remaining callers directly, and before the final switch-off do an announced brownout — return 410 for an hour and see who complains. Without usage data the answer is always "leave it running", and versions accumulate forever.

Q: Is there a way to avoid versioning?

Mostly, yes, and that is the better default. Design additively — new optional fields, new endpoints, tolerant readers on both sides — and most changes need no version at all. Every version you add is a code path you maintain, test and support indefinitely, and the real cost is often in the data layer rather than the controller, because two versions over one schema still have to agree on what the data means. Version when the change genuinely cannot be additive, not as a matter of routine.


Traps ⚠️

  • Header versioning without Vary — proxies serve one version's cache to another.
  • Microsoft.AspNetCore.Mvc.Versioning is the dead package name. Use Asp.Versioning.*.
  • No default version and no AssumeDefaultVersionWhenUnspecified → 400 for unversioned clients.
  • Turning that setting on is one-way — the default can then never change.
  • Versioning without usage metrics means you can never retire anything.
  • Behavioural changes are breaking even when the schema is identical.
  • Sharing a base class between a frozen v1 and an active v2 drags changes into v1.
  • Versioning the controller but not the data model — the hard part is the schema.
  • A version per sprint. Versions are a cost, not a changelog.
  • Forgetting SubstituteApiVersionInUrl leaves a literal {version} in Swagger's URLs.


Sources