API versioning never becomes a real concern on the first endpoint you ship. It becomes one the day you need to change a response shape while a mobile app you no longer control, because not every user has updated, still depends on it. At that point "we'll just tweak the endpoint" turns into a silent breaking change for a client you can't force to update right now.
Compatible change versus breaking change
Every versioning discussion starts from this distinction, and it's stricter than it looks. Adding an optional field to a JSON response is generally safe, provided clients ignore unknown fields (the default behavior of most JSON parsers, though not a universal guarantee). Renaming a field, changing its type (an integer that becomes a string), changing the meaning of an HTTP status code, or making a previously optional parameter required are all breaking changes, even when they look minor on the server side.
The three versioning strategies
URI versioning (/api/v1/orders, /api/v2/orders) is the most visible and easiest to route, but it bakes a version into the URL: a client that bookmarks or caches a URL stays pinned to that version, and routing several complete versions in parallel gets heavy to maintain fast.
Header versioning (Accept: application/vnd.myapi.v2+json, or a custom X-API-Version: 2 header) keeps URLs stable, which is cleaner in REST terms (the URI identifies the resource, not its representation), but makes manual debugging harder (you can't just paste a URL into a browser) and requires finer content negotiation setup.
Query parameter versioning (?version=2) is the simplest to implement but pollutes URLs and interacts poorly with standard HTTP caching, which often treats the query string as part of the cache key inconsistently across intermediaries.
// Express: custom header versioning, resolved in a middleware
app.use("/api/orders", (req, res, next) => {
const version = req.header("X-API-Version") || "1";
req.apiVersion = version;
next();
});
app.get("/api/orders/:id", (req, res) => {
const order = getOrder(req.params.id);
if (req.apiVersion === "2") {
return res.json(serializeOrderV2(order));
}
return res.json(serializeOrderV1(order));
});
In practice, most serious public APIs (Stripe, GitHub) use some variant of header or date-based versioning (Stripe-Version: 2024-06-20), precisely because it decouples URL stability from the evolution of the data contract.
The pattern that avoids a breaking cutover: expand-contract
Rather than swapping a field overnight, the expand-contract pattern (also called parallel change) rolls the change out in three stages: first add the new field alongside the old one (expand), gradually migrate consumers onto the new field, and only remove the old one once no active client is still using it (contract).
// "expand" phase: both fields coexist in the same response
{
"id": "ord_123",
"amount_cents": 4999,
"amount": 49.99
}
The contract step should never be a calendar decision ("we'll revisit in three months") but a data-driven one: instrument actual usage of the old field (access logs, application metrics on which clients send which version header) before removing it.
Communicating deprecation without surprising anyone
RFC 8594 defines a standardized Sunset header, and common practice pairs it with a Deprecation header to flag that an endpoint or version is on its way out well before the actual cutoff date.
HTTP/1.1 200 OK
Content-Type: application/json
Deprecation: true
Sunset: Sat, 31 Dec 2024 23:59:59 GMT
Link: <https://api.example.com/docs/migration-v2>; rel="deprecation"
{"id": "ord_123", "amount": 49.99}
A well-written client can log or alert the moment it sees Deprecation: true, which gives real visibility into migration adoption, far more reliable than a notification email that some consuming teams will never read.
Diagnosing who still depends on the old version
Before removing anything, you need to know who still uses it, not assume. Two concrete tools: a per-version/endpoint counter in application metrics (Prometheus with an api_version label), and a review of access logs over a representative window (at least one full billing cycle if the API exposes financial data, to catch integrations that only call it once a month).
-- query against an access log table to find the last callers of v1
SELECT client_id, MAX(called_at) AS last_call
FROM api_access_log
WHERE endpoint = '/api/orders' AND api_version = '1'
GROUP BY client_id
HAVING MAX(called_at) > now() - interval '30 days'
ORDER BY last_call DESC;
Versioning the parts clients don't see directly
Not every breaking change comes from a field rename. Pagination defaults, rate limit thresholds, and error response shapes are part of the contract just as much as the resource body, and teams routinely version the first without thinking to version the second. A client built against an API that returns {"error": "message string"} breaks just as hard when that shape becomes {"error": {"code": "...", "message": "..."}}, even though the change looks like an improvement from the server's side.
// before: error responses are a flat string
{ "error": "Order not found" }
// after: a structured error, which is still a breaking change
// for any client that was doing error.toUpperCase() on the old shape
{ "error": { "code": "ORDER_NOT_FOUND", "message": "Order not found" } }
The practical fix is to version error shapes through the exact same mechanism as the resource body, rather than treating error responses as an implementation detail exempt from the contract. If the API versions by header, the error serializer needs to branch on that header too; if it versions by URL, the error-handling middleware needs to know which version segment it's responding under. Skipping this is one of the most common ways a "v2 migration" ships clean on the happy path and breaks error handling in client code that nobody tested against failure cases.
Testing for contract regressions
An unintentional contract change usually slips in without anyone meaning to introduce it, like a refactor that changes serialization order and turns an optional field into null instead of leaving it absent. Contract testing (a consumer-driven tool like Pact, or simply an automated OpenAPI schema diff in CI) catches these regressions before they reach production, well before an external client reports them through support.
Automating breaking-change detection in CI
Relying on human vigilance in code review to catch a renamed field in a JSON response doesn't hold up over time. The better practice is to generate an OpenAPI schema from the code itself (via framework annotations, such as springdoc-openapi on Spring or @nestjs/swagger on NestJS), then diff that schema against the previous version on every pull request.
# .github/workflows/api-contract-check.yml
name: API contract check
on: [pull_request]
jobs:
contract-diff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Generate current OpenAPI spec
run: ./scripts/generate-openapi.sh > openapi-current.json
- name: Diff against main
run: |
git show main:openapi.json > openapi-main.json
npx oasdiff breaking openapi-main.json openapi-current.json --fail-on ERR
oasdiff breaking explicitly fails CI if the diff contains a change classified as breaking (a removed field, a changed type, a parameter that became required), which turns a discipline rule into an automated check rather than a hope that nobody misses it in review. A deliberately breaking change is still possible, but it then has to be explicitly owned (a major version bump, migration docs), not slipped quietly into a refactor that looked harmless.
When the easy fix isn't enough
Header or URL versioning answers "how do multiple versions coexist," not "for how long." If a version needs to stay alive for years because an enterprise client runs on a contractually slow upgrade cycle, the real question becomes organizational: who bears the cost of maintaining two diverging implementations in parallel, and at what number of active versions does that debt become more expensive than negotiating an end-of-support date with that client. No technical pattern solves that; it's a product tradeoff that needs to be made explicit rather than letting the number of active versions grow indefinitely by default.
Versioning an API correctly means treating the contract with existing clients as a commitment, not an implementation detail you can change on the next deploy. The discipline that pays off over time is less about which strategy you pick (URI, header, or otherwise) and more about the rigor of instrumenting who still depends on what before you cut anything off.
