📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What are the main API versioning strategies: URL segment, query string, header and media type? Compare them, explain how the Asp.Versioning library supports each in ASP.NET Core, and tell me when you would avoid introducing a new version at all.

Compares URL, query string, header and media type API versioning, how Asp.Versioning implements them on .NET 10, and when evolving without a new version is the better choice.

Intermediate Theory Intermediate api-design api-versioning asp-versioning aspnet-core backward-compatibility web-api

🎯 Key points

  • Four schemes: URL segment /v1/, query ?api-version=, header (api-version or custom), media type parameter in Accept
  • URL segment is most visible and cache-friendly but changes the resource URI
  • Asp.Versioning ApiVersionReader.Combine lets one API accept several schemes
  • ReportApiVersions adds api-supported-versions and api-deprecated-versions headers
  • Version only for breaking changes; additive changes ship without a new version
  • A version is a support commitment: every live version costs testing, docs and on-call
  • AssumeDefaultVersionWhenUnspecified eases migration but hides clients that never send a version
  • Asp.Versioning 10.x targets .NET 10 and its built-in OpenAPI

⏱ 30-second answer

There are four common schemes: URL segment (/v1/orders), query string (?api-version=1.0), a request header (api-version: 1.0) and a media type parameter (Accept: application/json;v=1.0). In ASP.NET Core the Asp.Versioning library (10.x for .NET 10) implements all four through an ApiVersionReader, and can combine them.

  • URL segment is the most visible, easiest to route, cache and test in a browser, which is why most public APIs use it.
  • Header and media type keep URIs stable but are invisible in logs and links and easy for clients to forget.

The senior part: version only for breaking changes. Additive changes (new optional fields, new endpoints) should ship without a version bump, because every live version is a support cost you carry for years.

🗣 Full answer (senior)

How I would answer this in an interview

"API versioning is how you let an API make breaking changes without breaking the clients already using it. There are four common places to put the version: in the URL path, like /v1/orders; in the query string, like ?api-version=1.0 (Azure's own REST APIs use a date there, such as 2024-10-01); in a custom request header; or as a parameter on the media type in Accept. In ASP.NET Core I use the Asp.Versioning library, now on the 10.x line for .NET 10, where each scheme is an ApiVersionReader and you can combine them with ApiVersionReader.Combine, so one API can accept a URL segment for humans and a header for clients that prefer it.

The trade-off is visibility against purity, and it affects clients and caches differently. A URL segment is obvious in logs, browser address bars, Application Insights and gateway routing rules, and it caches cleanly because the version is part of the path. A query string is also part of the cache key in standards-compliant caches, but some CDN rules are configured to ignore or strip query strings, and client code that builds URLs by hand tends to drop it, so unversioned calls quietly fall back to the default. Header and media type versioning keep URIs clean but need Vary for caching and are invisible when someone pastes a URL into a ticket. For a public or partner API I default to the URL segment for the major version; for internal APIs on Azure I'm happy with a query string version.

The mistake I see is versioning too eagerly. Teams bump to v2 for adding a field, and two years later they're running four versions, each with its own tests, docs and bugs. Adding optional fields, new endpoints or new optional query parameters is not breaking if clients are tolerant readers, so it shouldn't need a version. I save a new major version for genuine breaks: removing or renaming a field, changing a type, tightening validation or changing semantics. A version is a promise, so I make as few of them as I can and give each one a published sunset date."


The four schemes

Scheme Example Strengths Weaknesses Effect on clients
URL segment GET /v1/orders/42 Visible, routable, cacheable, easy to test with curl Version is in the resource identity; links break across versions Clients must rewrite base URLs to migrate; very hard to forget
Query string GET /orders/42?api-version=1.0 Optional, defaults easily, used by Azure REST APIs Easy to drop when building URLs; CDN rules that ignore query strings serve the wrong version Silent fallback to the default version if omitted
Header api-version: 1.0 Clean URIs Invisible in logs and links; CORS must allow it; needs Vary SDKs handle it well; hand-written clients forget it
Media type Accept: application/vnd.shop.v1+json or application/json;v=1.0 Most REST-faithful; versions the representation Hard for clients; needs Vary: Accept; weaker tooling Content negotiation errors (406) confuse less experienced integrators

What Asp.Versioning gives you

Feature What it does
ApiVersionReader (UrlSegment, QueryString, Header, MediaType) Where the version is read from; Combine accepts several
ReportApiVersions = true Adds api-supported-versions and api-deprecated-versions response headers
AssumeDefaultVersionWhenUnspecified Treats unversioned calls as the default version, useful when retrofitting
Version sets and HasApiVersion / MapToApiVersion Map Minimal API endpoints or controller actions to versions
Sunset policies Emit a Sunset header (RFC 8594) with a link to the deprecation notice
Asp.Versioning.OpenApi (10.x) One OpenAPI document per version with the built-in .NET 10 OpenAPI support

Version numbers: semantic or date?

Format Example Fits
Major only v1, v2 Public APIs where only breaking changes bump the version
Major.minor 1.0, 1.1 When you want to signal additive changes too (clients still shouldn't need to send minor)
Date 2025-11-01 Azure-style platforms; many small breaking changes, each pinned by date

Why teams pick each in practice

  • Public partner APIs (Stripe-like, banking open data style) pick URL majors because integrators of every skill level must get it right first time.
  • Azure-style platforms with hundreds of resource types pick query string dates because each resource evolves on its own schedule.
  • Internal service meshes with generated SDKs often pick headers, because the SDK sets it and URIs stay stable for gateway rules.

When not to version

  • The change is additive and clients ignore unknown fields.
  • You own every client and can deploy them together (version the deployment, not the API).
  • The change can be made opt-in with a new optional parameter or a new endpoint.

Production example

On a partner API with [N] integrators, we used /v1/ URL segments and ReportApiVersions. Over 18 months we shipped roughly 40 additive changes without a version bump, and one v2 for a pricing model change. We ran v1 and v2 side by side for 12 months, watched the per-version request count in Application Insights fall from [X]% to under 1%, then retired v1 on the published sunset date.

🔍 What the interviewer is checking

Checks that the candidate knows the versioning schemes and the Asp.Versioning tooling, and, more importantly, has a policy for when to version and how to retire versions.

Green flags

  • Compares schemes on visibility, caching (Vary) and client ergonomics
  • Says additive changes don't need a new version
  • Knows ReportApiVersions, version readers and the current Asp.Versioning package line
  • Mentions sunset dates and measuring per-version traffic

Red flags

  • Thinks there is one correct scheme for every API
  • Bumps the version for every release
  • Duplicates the domain or database per version
  • Has never retired a version

📚 Learn in depth

1. What "version" really means

A version identifies a contract: the shape of requests and responses, the status codes, and the behaviour. A breaking change is any change that makes a correct existing client fail or behave wrongly. Versioning exists to let old and new contracts run side by side while clients migrate.

client (built against v1) ──► gateway ──► API
                                   │
                     reads version (path / query / header / media type)
                                   │
                    ┌──────────────┴──────────────┐
                 v1 handlers                   v2 handlers
                 (old contract)                (new contract)
                    └───────── shared domain and database ─────────┘

The important design point is the bottom line: versions usually differ at the edge (DTOs, mapping, validation), not in the domain. If v1 and v2 need different databases, it's a new product, not a new version.

2. How Asp.Versioning selects an endpoint

Asp.Versioning plugs into endpoint routing. Each endpoint carries ApiVersionMetadata. At request time:

  1. The configured IApiVersionReader extracts the raw version (one or more readers via Combine).
  2. IApiVersionParser turns it into an ApiVersion (major, minor, optional group date, status).
  3. A matcher policy filters candidate endpoints by version.
  4. If none match, the library returns 400 (UnsupportedApiVersion) or a 404/405 depending on what matched, as a ProblemDetails body.
  5. If ReportApiVersions is on, response headers list supported and deprecated versions.

Because it is endpoint metadata, the same information feeds API Explorer, which is what produces one OpenAPI document per version.

3. Caching and versioning

HTTP caches key on the URI plus whatever the Vary header lists.

  • URL segment or query string: the version is in the URI, so caching works automatically.
  • Header or media type: you must send Vary: api-version or Vary: Accept, or a CDN can serve a v1 body to a v2 client. Many CDNs handle Vary poorly, which is a practical reason to prefer the URL.

4. Versioning granularity

Granularity Meaning Trade-off
Whole API /v2/ applies to every resource Simple to explain; forces clients to move everything at once
Per resource or endpoint /orders is v2 while /customers stays v1 Less churn; harder to document and reason about

Asp.Versioning supports both: version sets can be shared across a route group or declared per endpoint. Most teams pick whole-API major versions and let minor changes be additive.

5. Alternatives to a new version

  • Expand and contract: add the new field, keep the old one populated, deprecate it, remove it in the next major.
  • New endpoint for the new behaviour (POST /payments/refunds alongside the old refund action).
  • Opt-in parameter (?include=lineItems) for heavier responses.
  • Feature flags per client for behaviour changes during migration.

6. Older versions of the library

The library used to be Microsoft.AspNetCore.Mvc.Versioning; it was renamed to Asp.Versioning.* (v6) when it moved to the .NET Foundation. Interviewers sometimes still use the old name. On .NET 10 use the 10.x packages: Asp.Versioning.Http for Minimal APIs or Asp.Versioning.Mvc for controllers, plus Asp.Versioning.Mvc.ApiExplorer and, for the built-in OpenAPI, Asp.Versioning.OpenApi.

Try it yourself

  1. Create a Minimal API with Asp.Versioning, map GET /v{version:apiVersion}/orders/{id} for 1.0 and 2.0, and call both with curl. Check the api-supported-versions header.
  2. Switch to ApiVersionReader.Combine(new UrlSegmentApiVersionReader(), new HeaderApiVersionReader("api-version")) and confirm a conflicting header and path return 400.
  3. Call an unsupported version (/v9/orders/1) and read the ProblemDetails body.
  4. Turn on AssumeDefaultVersionWhenUnspecified and log how many requests arrive without a version over a day; that's your hidden migration risk.
  5. Put a header-versioned endpoint behind a cache without Vary and reproduce serving the wrong version.

💻 Code

Minimal API versioning with Asp.Versioning 10.x on .NET 10: URL segment for humans, header accepted too, versions reported in responses.

// Program.cs
using Asp.Versioning;

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddApiVersioning(options =>
    {
        options.DefaultApiVersion = new ApiVersion(1, 0);
        // Retrofit only: treat unversioned calls as 1.0, but log them so you can chase those clients.
        options.AssumeDefaultVersionWhenUnspecified = true;
        // Adds api-supported-versions / api-deprecated-versions response headers.
        options.ReportApiVersions = true;
        // Accept the version in the path or in a header; a conflict between them returns 400.
        options.ApiVersionReader = ApiVersionReader.Combine(
            new UrlSegmentApiVersionReader(),
            new HeaderApiVersionReader("api-version"));
    })
    .AddApiExplorer(options =>
    {
        options.GroupNameFormat = "'v'VVV";        // v1, v2 document names
        options.SubstituteApiVersionInUrl = true;  // /v{version} becomes /v1 in OpenAPI
    });

var app = builder.Build();

var orders = app.NewVersionedApi("Orders");

var v1 = orders.MapGroup("/v{version:apiVersion}/orders").HasApiVersion(1.0);
v1.MapGet("/{id:int}", (int id) => TypedResults.Ok(new OrderV1(id, 120.50m)));

var v2 = orders.MapGroup("/v{version:apiVersion}/orders").HasApiVersion(2.0);
// v2 is a breaking change: money becomes an object with a currency.
v2.MapGet("/{id:int}", (int id) => TypedResults.Ok(new OrderV2(id, new Money(120.50m, "AUD"))));

app.Run();

public sealed record OrderV1(int Id, decimal Total);
public sealed record Money(decimal Amount, string Currency);
public sealed record OrderV2(int Id, Money Total);
curl -i https://localhost:5001/v1/orders/42
# HTTP/1.1 200 OK
# api-supported-versions: 1.0, 2.0
curl -i -H "api-version: 2.0" https://localhost:5001/v1/orders/42
# HTTP/1.1 400 Bad Request  (ambiguous: path says 1.0, header says 2.0)

⚠ Common mistakes

  • Mistake: Creating a new version for every additive change. Why it is wrong: Each live version multiplies testing, documentation and support cost, and clients never catch up. Instead: Ship additive changes in place and reserve new majors for real breaks.
  • Mistake: Header or media type versioning behind a CDN without Vary. Why it is wrong: The cache keys only on the URI, so it serves a v1 body to a v2 client. Instead: Send Vary: api-version (or Accept), or use URL or query versioning.
  • Mistake: Query string versioning behind a CDN rule that ignores query strings. Why it is wrong: Every version shares one cache entry. Instead: Include the api-version parameter in the cache key explicitly, or version in the path.
  • Mistake: Leaving AssumeDefaultVersionWhenUnspecified on forever. Why it is wrong: You can never move the default without breaking silent clients you can't identify. Instead: Use it during a retrofit, log unversioned calls, and require a version for new clients.
  • Mistake: Forking the domain logic and database schema per API version by default. Why it is wrong: It duplicates business rules and makes fixes land in one version but not another. Instead: Keep one domain and version DTOs and mapping at the edge; separate storage per version is justified only for a deliberate re-platforming or a time-boxed migration, and then it should be planned and retired like any migration.
  • Mistake: No sunset date for old versions. Why it is wrong: Versions live forever, and the team carries them into every upgrade. Instead: Publish a deprecation policy (for example 12 months' notice) and emit Sunset headers.
  • Mistake: Still referencing Microsoft.AspNetCore.Mvc.Versioning on .NET 10. Why it is wrong: It's the old, unmaintained package name. Instead: Use the Asp.Versioning.* 10.x packages.
  • Mistake: Mixing schemes inconsistently across services. Why it is wrong: Clients must learn a different rule per service, and gateways can't route uniformly. Instead: Pick one scheme in the organisation's API guidelines.

🏛 Senior insight: trade-offs

Versioning is a product decision dressed up as a technical one. The scheme matters far less than the policy: what counts as breaking, how long you support a version, how you tell clients, and how you measure who is still on the old one. I want per-version request counts in Application Insights or API Management from day one, because the conversation with a partner about retiring v1 goes much better with their own traffic numbers in hand.

Option When it fits Cost When not to
URL segment major version Public and partner APIs, gateways routing by path Version in resource identity; links differ per version Hypermedia-heavy APIs where URIs must be stable
Query string (date) Azure-style internal platforms with frequent small changes Many versions to track; easy to drop the parameter Public APIs consumed by less experienced developers
Header Internal clients you control Invisible in logs; needs Vary and CORS config Browser-tested or CDN-cached APIs
No versioning, additive only Internal APIs with tolerant clients and coordinated deploys Discipline: never break; contract tests needed Any API with clients you can't upgrade (mobile, partners)

I measure success by how rarely we need a new major version, not by how neatly we version.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions one OpenAPI document per version or detecting breaking changes Why: Checks that versioning is backed by automated contract checks in CI, not just conventions.
    How to answer

    I make the committed build-time spec the contract and gate pull requests on it:

    1. Drift check: rebuild and fail if the generated spec differs from the committed one.
    2. Breaking-change check: oasdiff breaking compares the PR's spec with main and the last released spec, and fails on removed paths or properties, new required request fields, narrowed enums or changed types.
    3. Lint: Spectral rules for house style (operationIds, ProblemDetails errors, naming).
    4. Versioning: one document per major version (AddOpenApi("v1"), AddOpenApi("v2")), so breaking changes go into a new version while v1 stays frozen.

    The trade-off: CI becomes stricter and occasionally needs a deliberate override, but breaking changes become explicit decisions instead of production incidents.

  2. When: Candidate says versions differ only at the edge in DTOs Why: Checks the candidate separates domain models from versioned DTOs and knows the mapping cost.
    How to answer

    A domain model represents business concepts with behaviour and invariants (an Order that can be paid, cancelled, and refuses invalid changes). A DTO (data transfer object) is a flat, behaviour-free contract for moving data across a boundary: an HTTP request or response, a message, a query result. Keep them separate so that the API contract and the domain can change independently, so clients cannot over-post fields they must not set (IsAdmin, Status), and so internal data does not leak in responses. Map with explicit code, source-generated mappers (Mapperly) or EF Core projections straight to DTOs for reads. Sharing one type is acceptable only for simple CRUD with no rules, and even then be careful at public boundaries.

  3. When: Candidate mentions sunset dates or deprecation policy Why: Checks the candidate can run a deprecation end to end: measurement, communication, headers and brownouts.
    How to answer

    Measure first: per-version and per-client traffic from Azure API Management or Application Insights, so you know exactly which of the 30 partners still call v1 and how much. Publish a deprecation notice with a date (for example 12 months), emit Deprecation (RFC 9745) and Sunset (RFC 8594) headers with a Link to the migration guide, and contact each partner directly with their own numbers.

    • Support the move: a migration guide with a v1→v2 field map, a sandbox, an FAQ and a named contact; ask for feedback and fix the blockers partners raise.
    • Track it: a per-partner migration dashboard, chased monthly.
    • Flush out silent clients: scheduled brownouts in the final months, then 410 Gone with a ProblemDetails body pointing to v2.

    The trade-off is time and support effort against the cost of running two versions.

↩ Usually asked after

More in API Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me