Back to all posts
API Versioning Best Practices: Decide What Breaks First
Software DevelopmentNovember 21, 2026

API Versioning Best Practices: Decide What Breaks First

A team adds an OnHold value to the order status its API returns, without a version bump, because adding is supposed to be backward compatible. The next morning a partner's .NET integration fails on every order list containing a held order: its client maps enums by name, and System.Text.Json throws on a name it has never seen. Most API versioning best practices start with /v2/ in the URL versus a header. That is the cheapest decision you will make. Three others cost real money: a definition of what breaks a client, measured against how your consumers deserialize; a scheme chosen by who those consumers are; and a retirement procedure that tells you when an old version can really be switched off. This article covers all three on .NET 10 with Asp.Versioning 10, verified by running it.

API Versioning Best Practices: The Short Answer

Version only for breaking changes, defined by what your consumers' deserializers do, not by whether a change adds or removes something. Prefer expand-and-contract, because every live version is a code path you keep testing. Pick one scheme for your slowest consumer and require the version on every request. Announce retirement with the Deprecation and Sunset headers, count who still calls the old version, and remove it when that count is zero.

What Actually Breaks a Client: Four Changes Measured on .NET 10

Google's AIP-180 splits compatibility into source (old code still compiles), wire (an old client can still talk to the new server) and semantic (an old client still gets what a reasonable developer would expect). A change can pass the first two and fail the third, which is why "it still deserializes" is not the test. The useful definition of breaking is the one your consumers' deserializers enforce. For .NET consumers that is usually System.Text.Json, run here on .NET 10 with web defaults and a string enum converter:

public enum OrderStatus { Pending, Paid, Shipped }
public record Order(int Id, OrderStatus Status);

var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
options.Converters.Add(new JsonStringEnumConverter());

// {"id":1,"status":"Paid","currency":"EUR"}  -> Order { Id = 1, Status = Paid }     extra field ignored
// {"id":1}                                    -> Order { Id = 1, Status = Pending }  missing field, silent default
// {"id":1,"status":"OnHold"}                  -> JsonException                      unknown enum name

Adding a Response Field

Adding a response property is the change most teams treat as always safe, and for System.Text.Json clients it usually is: by default, payload properties the target type does not declare are ignored. That leniency lets a server grow without a new version for every field, which keeps the number of live versions low. It stops being safe for a client that opted into strictness: since .NET 8, JsonUnmappedMemberHandling.Disallow makes the same payload throw, and a consumer validating against a JSON Schema with additionalProperties set to false rejects it too. The common mistake is assuming every consumer is lenient because your own clients are. The consequence is a breaking change shipped without a version bump and discovered by the consumer in production.

Removing or Renaming a Field

Removing or renaming a response property looks like an obvious break, but for a .NET client it rarely produces an error. A missing property gets the type's default: an int becomes 0, a string becomes null, an enum becomes its member with value 0, here Pending, a valid business state rather than a failure. That is worse than a loud break: the client keeps running and writes wrong values downstream. Two settings added in .NET 9, RespectNullableAnnotations and RespectRequiredConstructorParameters, turn a null in a non-nullable property and a missing constructor parameter into exceptions, but both are off by default, including under the web defaults. Removal without a new version is acceptable only when you own every consumer and have searched their code for the field. The common mistake is treating a rename as cosmetic and fixing the mapping only on the server. The consequence is weeks of wrong reports before anyone suspects your deploy.

Adding an Enum Value

A new response enum value is the change most often misclassified as additive. A client that maps enums by name throws a JsonException for the whole payload, so one held order fails the entire list. A client mapping enums as integers fails silently instead: {"status":7} deserialized into an undefined value, and every switch falls into its default branch. New values are safe for enums that only appear in requests, which AIP-180 allows freely because the server is the only reader. For response enums they are acceptable without a new version only if the contract declared the enum open from the start: Azure's REST guidelines use extensible enums (x-ms-enum with modelAsString), and oasdiff honours x-extensible-enum, both on the condition that clients fall back to default logic for unknown values. The mistake is documenting an enum as closed and treating it as open. The consequence is an outage on the consumer side caused by your deploy, with nothing in either changelog to explain it.

Tightening a Request

Tightening a request means adding a required property, narrowing validation, or changing the value the server applies when a field is omitted. These break clients that send exactly what used to be valid: AIP-180 forbids new required fields on existing requests and calls a changed default breaking, and oasdiff flags a new required request property because old requests become invalid. A new required field is fine on a new endpoint or version, and a new optional field whose default reproduces the old behaviour is fine anywhere. The common mistake is the changed default: same type, still optional, only the behaviour moved. Clients that omit the field get different results with status 200, which takes far longer to diagnose than a 400.

Turning the Four Cases into a CI Check

Write these cases down as your compatibility policy. A policy saying "additive changes are non-breaking" gets the enum case wrong and treats removal as a loud break when it is a silent one, producing version bumps nobody needed and breaks nobody announced. Skip the document when every consumer ships from the same repository in the same deployment; the compiler and integration tests already are the policy. Elsewhere, enforce it mechanically. The opt-in Asp.Versioning.OpenApi package generates one OpenAPI document per version; export them at build time and diff each against main on every pull request:

# fail the build on definite breaking changes in the v2 contract
oasdiff breaking openapi-main/v2.json openapi/v2.json --fail-on ERR

oasdiff reports ERR for definite breaks and WARN for ones it cannot confirm programmatically. Changed defaults are INFO and stay silent unless a --severity-levels file raises them to err; defaults set only in server code stay a review item.

Who Consumes the API Decides the Versioning Scheme

The scheme is how a request states which contract it expects, and the right one depends on how fast consumers move: your own service adopts a new contract in a day, a partner on its release calendar, a mobile app as fast as users install updates. Choose for the slowest consumer, and use one scheme across the API so gateways and logs treat every endpoint alike. Asp.Versioning supports all three options below; its default reader accepts query string and URL segment together.

URL Segment Versioning

URL segment versioning puts the version in the route, /api/v2/orders, read through a {version:apiVersion} route constraint. It is the most visible option: the version appears in access logs, gateway rules and support tickets without decoding a header. It is the wrong choice for clients that store resource URIs (webhook targets, emailed links), because every version bump changes a resource's address, and under Azure's guidelines, which forbid version segments in paths. The common mistake is copying every endpoint into a v2 group because one resource changed and the prefix is shared. Operationally, an unsupported version always returns 404 (our request to /api/v9/orders/5 did), so a client on a retired version sees the same status as a missing order, and 404 alerting cannot tell them apart.

Query String or Header Versioning

Here the version travels as ?api-version=2026-11-01 or in a header, and routes stay stable across versions, so stored client links survive a contract change. Azure makes it mandatory: api-version is a required query parameter on every operation; a request without it gets 400 with MissingApiVersionParameter, and values use YYYY-MM-DD. Header versioning is the wrong choice behind a cache or CDN that keys only on the URL, because it will serve a cached v1 body to a v2 caller unless told to vary on the header. The common mistake is enabling AssumeDefaultVersionWhenUnspecified so callers who omit the version get 1.0; it is off by default, and the library's documentation reserves it for legacy services that never supported versioning. Turn it on and unversioned callers ride the oldest version without showing up as its users, which stops you from ever retiring it.

Per-Consumer Date Pinning

Date pinning fixes each consumer to the version current when it integrated, allows a per-request override, and keeps server-side transformations that render older shapes. Stripe is the reference: requests use the account's default version unless the Stripe-Version header overrides it, and since 2024-09-30.acacia it ships monthly versions without breaking changes plus two major releases a year that may contain them. Consumers upgrade on their own schedule while the server ships continuously. It is the wrong choice for most teams: it needs per-consumer state and a transformation for every breaking change ever made, which pays off with thousands of integrations, not five partners. Stripe does not let its .NET SDK target another API version, since a strongly typed client cannot safely read another version's shapes. The common mistake is copying the header without the pinning, so a missing header means latest and every forgetful client gets a breaking change on deploy day. Underestimate the model and every old version stays in the request path permanently.

Internal Services: When Not to Version at All

Where you own both sides, a new version is often the wrong tool. Expand and contract does the same job with one code path: add the new field, deploy the consumers that read it, remove the old field later. Inside a modular monolith the compiler enforces it; between separately deployed services it depends on a real deploy order, covered in distributed systems architecture that holds up. Versioning pays once a consumer deploys on a schedule you do not control. The internal mistake is versioning HTTP endpoints carefully while changing event payloads freely, although a consumer replaying old events from a topic is the slowest consumer of all, and its replay fails on payloads nobody emits anymore.

Configuring Asp. Versioning 10 Without the Default Traps

This is the URL segment variant for Minimal APIs (Asp.Versioning.Http; controllers use Asp.Versioning.Mvc), built and run against 10.2.3 on .NET 10. Each setting overrides a default that would otherwise do something different. Skip the library while each route group has one live version; a plain MapGroup("/api/v2") is enough until two must run side by side.

builder.Services.AddApiVersioning(options =>
{
    // The default reader combines query string and URL segment; be explicit.
    options.ApiVersionReader = new UrlSegmentApiVersionReader();

    // Off by default. Without it no Deprecation, Sunset, or Link header is sent.
    options.ReportApiVersions = true;

    // Pass a UTC DateTimeOffset: Effective(2027, 5, 1) is read in server local time.
    options.Policies.Deprecate(1.0)
        .Effective(new DateTimeOffset(2026, 11, 1, 0, 0, 0, TimeSpan.Zero))
        .Link("https://api.example.com/docs/orders-v2-migration")
        .Title("Orders v1 to v2 migration")
        .Type("text/html");

    options.Policies.Sunset(1.0)
        .Effective(new DateTimeOffset(2027, 5, 1, 0, 0, 0, TimeSpan.Zero))
        .Link("https://api.example.com/docs/orders-v2-migration")
        .Title("Orders v1 to v2 migration")
        .Type("text/html");
});

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

orders.MapGroup("/api/v{version:apiVersion}/orders")
      .HasDeprecatedApiVersion(1.0)
      .MapGet("/{id:int}", (int id) => new { id, status = "Paid" });

orders.MapGroup("/api/v{version:apiVersion}/orders")
      .HasApiVersion(2.0)
      .MapGet("/{id:int}", (int id) => new { id, status = "Paid", currency = "EUR" });

A v1 request returns these headers, copied from the running app:

api-deprecated-versions: 1.0
Deprecation: @1793491200
Sunset: Sat, 01 May 2027 00:00:00 GMT
Link: <https://api.example.com/docs/orders-v2-migration>; rel="sunset"; title="Orders v1 to v2 migration"; type="text/html"
Link: <https://api.example.com/docs/orders-v2-migration>; rel="deprecation"; title="Orders v1 to v2 migration"; type="text/html"

Three details are easy to get wrong. With .Effective(2027, 5, 1) on a server at UTC+3, the header read Sunset: Fri, 30 Apr 2027 21:00:00 GMT, three hours early and on the wrong calendar day for any consumer automating against it. HasDeprecatedApiVersion only produces api-deprecated-versions; the standard Deprecation header comes from the policy. And version 10 turned many extension methods into properties, so v8 code calling GetRequestedApiVersion() no longer compiles; use RequestedApiVersion. Version 10.2 also enables analyzers by default, three at error severity, so an upgrade can fail a build.

Retiring a Version: Deprecation, Sunset, Then Removal

Retirement decides how many versions you run. Without a procedure, versions accumulate, each with its own handlers and tests, and nobody can say whether switching one off breaks a customer. Internal endpoints whose callers you deploy yourself skip the headers; expand and contract retire them faster. RFC 9745 (March 2025) standardises the Deprecation header and its relation to Sunset from RFC 8594. Following both:

  1. Publish the migration guide and link it with rel="deprecation". The RFC allows this link before any deprecation date exists.
  2. Send Deprecation with the date. Per RFC 9745, deprecation "does not change any behavior of the resource"; clients keep working.
  3. Send Sunset with the removal date, which the RFC says must not be earlier than the deprecation date.
  4. Count calls to the deprecated version per consumer, and contact every consumer that still appears.
  5. Remove the version when the count is zero, or at the sunset date for consumers that were contacted and agreed. For callers you cannot identify, run scheduled brownouts first, then answer 410 Gone with the migration link, not 404.

Teams skip step 4 because totals reassure. Count per client:

var meter = app.Services.GetRequiredService<IMeterFactory>().Create("Orders.Api");
var requestsByVersion = meter.CreateCounter<long>("orders.api.requests_by_version");

app.Use(async (context, next) =>
{
    await next(context);

    requestsByVersion.Add(1,
        new("api.version", context.RequestedApiVersion?.ToString() ?? "unspecified"),
        new("client.id", context.User.FindFirst("azp")?.Value ?? "anonymous"),
        new("http.response.status_code", context.Response.StatusCode));
});

The status code tag matters: our request to the unsupported /api/v9 still reported version 9. Keep client.id to application identities, never end users, or cardinality grows with your user base. A sunset date is not a removal trigger while a consumer under contract still calls the version; the date moves, and the header says so. The common mistake is removing on the announced date because it was announced. The consequence is a partner integration failing with a 404 on a Monday morning, and a rollback that means redeploying code you already deleted.

Where to Start

Do not start with the scheme. Write down what breaks your consumers, and enforce it with an OpenAPI diff in CI. Then pick the scheme for your slowest consumer and count calls per client from day one; that count makes the first retirement possible. API contracts, the services behind them, and the pipeline that enforces them are one piece of work, the kind of software development and DevOps engagement where we own the whole path from code to production.

#dotnet#Architecture