Complete Guide to API Versioning Strategies
Compare URI, header, query-param and content-negotiation versioning for REST, plus GraphQL schema evolution, deprecation and migration.
Introduction
Every public API eventually faces the same fork: freeze and stagnate, or evolve and break someone. Versioning exists so that fork isn’t forced on your consumers. API versioning is the mechanism that lets an API evolve without breaking the clients that already depend on it. Every shipped API is a contract: mobile apps pinned to an old build, partner integrations nobody wants to touch, scripts running in cron jobs someone forgot existed. Change the contract under them — rename a field, tighten a type, restructure a response — and those clients fail silently or loudly, usually in production.
The uncomfortable part: retrofitting versioning is painful, so the decision to version happens before you’ve got a versioning problem. This guide compares the four REST strategies (URI path, query parameter, header, content negotiation), covers GraphQL’s different model, and goes through the full lifecycle — deprecation, sunset, and migration — because publishing v2 is the easy half; retiring v1 without breaking anyone is the hard one. The strategies are HTTP-level decisions, not framework features — everything below applies whether you build in FastAPI, Express, or Spring.
Why Version APIs?
- Backward compatibility: existing clients keep working when you add or change fields — they don’t need a coordinated deploy with yours.
- Controlled breaking changes: introduce v2 while v1 still runs, so migration is a choice clients make, not an incident they discover.
- Clear deprecation timeline: consumers know when to migrate and you know when you can retire.
- Safe experimentation: test new behavior on a new version or a subset of traffic without affecting v1.
One nuance worth stating early: you version for breaking changes, not for every release. If a change is additive — a new field, a new endpoint — it ships on the current version. Reserve version numbers for changes that would break existing clients; otherwise you end up on /v17 for no reason.
Choosing a Strategy
Before the code, the decision:
There’s no universally right answer — the “best” strategy is the one your consumers will actually send correctly — but there’s a dominant one. URI path versioning won the market for public APIs because it makes the version impossible to miss: it’s in the URL, in the logs, in the CDN cache key, in every Stack Overflow answer. The alternatives trade that visibility for HTTP purity, which matters more to spec purists than to the developer integrating your API at 2am. The question isn’t “which is most RESTful” — it’s “which failure mode can your consumers best handle?” An invisible header version fails when someone forgets to send it; a visible /v2/ fails only if you remove it.
REST API Versioning Strategies
1. URI Path Versioning
The most common approach: the version is part of the URL. /api/v1/users and /api/v2/users are literally different resources, so routing, caching, logging, and documentation all work with zero special handling.
from fastapi import FastAPI, APIRouter
app = FastAPI()
v1_router = APIRouter(prefix="/api/v1")
v2_router = APIRouter(prefix="/api/v2")
@v1_router.get("/users/{user_id}")
async def get_user_v1(user_id: str):
return {"id": user_id, "name": "Alice", "email": "alice@example.com"}
@v2_router.get("/users/{user_id}")
async def get_user_v2(user_id: str):
return {"id": user_id, "name": "Alice", "email": "alice@example.com", "created_at": "2024-01-01"}
app.include_router(v1_router)
app.include_router(v2_router)
Pros: simple, explicit, cacheable, visible in logs, easy to route and deprecate. Cons: URI “pollution”, breaks REST purity (a version isn’t a resource), and encourages maintaining whole parallel route trees.
In practice the cons matter less than they sound — every major public API (Stripe, Twilio, GitHub) uses some variant of path versioning, because consumers read URLs more than headers. Mount versions at the router level (as above) rather than duplicating endpoints, so the v1 tree stays frozen while v2 evolves.
2. Query Parameter Versioning
The version travels as a query param: /users/123?version=2. URIs stay clean and it’s trivial to default to the latest when the param is absent.
from fastapi import FastAPI, Request, HTTPException
app = FastAPI()
@app.get("/users/{user_id}")
async def get_user(user_id: str, request: Request):
version = request.query_params.get("version", "1")
if version == "1":
return {"id": user_id, "name": "Alice"}
elif version == "2":
return {"id": user_id, "name": "Alice", "email": "alice@example.com"}
raise HTTPException(status_code=400, detail="Unsupported version")
Pros: clean URIs, easy default-to-latest, no extra headers. Cons: invisible in logs unless you log query strings, easy for clients to forget, and caching is fragile — a shared cache key must include the param or v1 and v2 responses mix.
The caching caveat is the real gotcha: if a CDN or proxy doesn’t treat ?version= as part of the cache key, one client can poison the cache with the other version’s payload. Defaulting absent params to “latest” also seems friendly until a client that meant v1 silently gets v2 after a deploy — pin the default to a version and migrate deliberately, or require the param explicitly.
3. Header Versioning
The version moves out of the URI entirely into a custom header — typically X-API-Version: 2. The URI describes the resource; the header describes the contract.
from fastapi import FastAPI, Header, HTTPException
app = FastAPI()
@app.get("/users/{user_id}")
async def get_user(
user_id: str,
x_api_version: str = Header(default="1", alias="X-API-Version"),
):
if x_api_version == "1":
return {"id": user_id, "name": "Alice"}
elif x_api_version == "2":
return {"id": user_id, "name": "Alice", "email": "alice@example.com"}
raise HTTPException(status_code=400, detail="Unsupported version")
Pros: clean URIs, RESTful (version is metadata, not resource), fine-grained.
Cons: invisible in logs and browser dev tools, harder to test by hand, and not cacheable by default — the cache must vary on the header — that’s Vary: X-API-Version on the response, plus a matching cache-key rule on any CDN in front; without it, a cached v1 body goes to a v2 client.
This is the strategy internal service meshes prefer: when both sides are your own code, a header is fine because nothing human needs to see it. For public APIs it’s a harder sell — a consumer poking your API with curl or a browser can’t see the version at all, and forgetting the header means silent defaulting to whichever version you picked.
4. Content Negotiation (Accept Header)
The “purist” option: the version is part of the media type itself, so /users/123 returns application/vnd.example.v1+json or application/vnd.example.v2+json depending on the Accept header the client sends.
from fastapi import FastAPI, Request, HTTPException
app = FastAPI()
@app.get("/users/{user_id}")
async def get_user(user_id: str, request: Request):
accept = request.headers.get("accept", "")
if "application/vnd.example.v1+json" in accept:
return {"id": user_id, "name": "Alice"}
elif "application/vnd.example.v2+json" in accept:
return {"id": user_id, "name": "Alice", "email": "alice@example.com"}
raise HTTPException(status_code=406, detail="Unsupported media type")
Pros: strictly RESTful (the media type carries the contract), follows the HTTP spec, cleanest possible URIs.
Cons: hardest for consumers — Accept: application/vnd.example.v2+json is a mouthful, browsers can’t test it, and Accept is already overloaded for format negotiation (JSON vs XML).
Content negotiation is the most correct and the least loved. It shines in hypermedia APIs and formal API programs (it’s what the GitHub API originally used before moving to X-GitHub-Api-Version), but for most teams the DX cost isn’t worth the purity gain — an Accept header nobody remembers to send correctly fails more often than a /v2/ path.
Comparison
| Strategy | Visibility | Caching | RESTful | Complexity | Best For |
|---|---|---|---|---|---|
| URI Path | High | Easy | No | Low | Public APIs, most common |
| Query Param | Medium | Harder | Yes | Low | Internal APIs, default-to-latest |
| Header | Low | Hard | Yes | Medium | Internal APIs, fine-grained |
| Content Negotiation | Low | Hard | Yes | High | Strict REST, media-type driven |
Read “Caching” carefully — it’s the column that bites in production. Path versions are free in every CDN and browser; anything in a header or query param requires the cache to vary on that key, and a cache that doesn’t returns the wrong version to the wrong client — a subtle, brutal failure mode that only shows up under real traffic.
GraphQL Schema Evolution
GraphQL rejected versioning by design — instead of freezing endpoints, the schema evolves. The rule of thumb: you can always add, you can never remove without breaking someone.
Additive changes (no version needed)
type User {
id: ID!
name: String!
email: String! # New field — old clients ignore it
createdAt: String # New field — nullable for backward compat
}
Deprecating fields
type User {
id: ID!
name: String!
email: String!
username: String @deprecated(reason: "Use email instead")
}
Breaking changes (new schema or directive)
const { buildSchema } = require("graphql");
// Option 1: Run two schemas on different endpoints
const v1Schema = buildSchema(`
type User { id: ID!, name: String! }
`);
const v2Schema = buildSchema(`
type User { id: ID!, name: String!, email: String! }
`);
// Option 2: Use @specifiedBy or custom directives for feature flags
const schema = buildSchema(`
type User {
id: ID!
name: String!
email: String
}
`);
GraphQL versioning best practices
- Add fields, never remove — old clients keep working because they only request what they know.
- Deprecate before removing — the
@deprecateddirective marks the field in the schema and in GraphiQL introspection. - Make new fields nullable — old data may not have the value; a non-null new field breaks queries against existing records.
- Use schema stitching/federation for major versions — route queries to a v1 or v2 subgraph instead of one monolith.
- Track field usage — only remove deprecated fields when query analytics show usage at zero; GraphQL makes this measurable because clients declare exactly which fields they want.
For deeper coverage see the GraphQL schema design guide.
Deprecation and Sunset
A version without an exit plan is a version forever. The industry-standard headers are Deprecation and Sunset — defined in the Internet-Draft that became the deprecation-header RFC lineage (RFC 8594 is the older Sunset draft; the modern header pair is Deprecation: true + Sunset: <HTTP-date>), and they’re machine-readable so API gateways and HTTP clients can warn automatically.
Deprecation headers
from fastapi import FastAPI, Response
app = FastAPI()
@app.get("/api/v1/users/{user_id}")
async def get_user_v1(user_id: str, response: Response):
response.headers["Deprecation"] = "true"
response.headers["Sunset"] = "Sun, 01 Jun 2025 00:00:00 GMT"
response.headers["Link"] = '</api/v2/users/{user_id}>; rel="successor-version"'
return {"id": user_id, "name": "Alice"}
The Link header pointing at the successor is the part everyone skips — and it’s the most useful: a client parsing it knows exactly where to go, no docs required.
Deprecation timeline
- Announce: add
Deprecation: true, update docs, publish a migration guide. - Notify: email API consumers; log deprecation warnings on every call.
- Sunset: add the
Sunsetheader with a removal date — minimum 6 months out, 12+ for public APIs. - Monitor: track usage of the deprecated endpoint — this decides your real deadline.
- Remove: after the sunset date, return
410 Gone— not 404 — so clients can distinguish “removed” from “wrong URL”.
Two details the timeline hides: monitor first, delete later — if the usage graph still shows traffic at sunset minus one month, you extend the deadline or accept breaking those clients knowingly; and a 410 Gone response is your last piece of documentation, so make the body point at the migration guide one final time.
Migration Patterns
There’s a useful asymmetry worth naming before the patterns: publishing a version is a code change; migrating consumers is a human change. The code ships when you’re ready — the migration finishes when they are. That’s why the techniques below all share one property: they decouple “v2 exists” from “v1 users moved”, so the first can be true for months while the second catches up.
Shipping v2 is easy; moving traffic off v1 without an outage is the project. Two patterns dominate.
Strangler Fig pattern
Route by path: new endpoints go to v2, old endpoints stay on v1, and migrated endpoints proxy through — so the facade URL never changes while the implementation underneath swaps out.
from fastapi import FastAPI, Request
import httpx
app = FastAPI()
@app.api_route("/api/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
async def router(path: str, request: Request):
# New endpoints handled by v2
if path.startswith("v2/"):
return await handle_v2(request)
# Old endpoints — check if migrated
migrated = ["users", "orders"] # endpoints that moved to v2
base_path = path.split("/", 1)[0] if "/" in path else path
if base_path in migrated:
# Proxy to v2 with response transformation
return await proxy_to_v2(request)
# Not migrated — serve from v1
return await handle_v1(request)
Parallel run (shadow deployment)
Run both versions against real traffic but serve only v1: v2 executes in the background, responses get compared, and mismatches are logged — so you discover v2’s differences on production data with zero production risk.
import asyncio
import logging
logger = logging.getLogger("api_migration")
async def parallel_run(v1_handler, v2_handler, request):
# Serve from v1 (source of truth)
v1_response = await v1_handler(request)
# Run v2 in background, compare results
try:
v2_response = await v2_handler(request)
if v1_response != v2_response:
logger.warning(f"Response mismatch: v1={v1_response}, v2={v2_response}")
except Exception as e:
logger.error(f"v2 handler failed: {e}")
return v1_response
The production caveat: shadow runs double the load for the shadowed endpoints — pick a traffic percentage, not all of it. Mismatch logging should capture the request too, or you’ll have diffs you can’t reproduce. Once mismatches stay at zero for a week, flip the source of truth and the pattern becomes a strangler cutover.
When NOT to Version
The contrarian part of versioning: sometimes the right answer is no version at all. Three cases where a new version is the wrong tool:
- Internal APIs with one consumer. If your own frontend is the only client and you deploy both together, versioning buys ceremony — deploy them as a unit and let the release pipeline be the contract. Versioning pays when clients deploy on your schedule, not theirs.
- Additive-only evolution. If every change you plan is a new field or endpoint, the version number is dead weight — GraphQL’s model applies to REST too: evolve additively, mark the old stuff deprecated, and the version stays 1 forever.
- The change is a bug fix. A broken response consumers built workarounds around is still a bug fix, not a breaking change — version the contract, not the implementation. If v1 documented
total: intand returned a string, fixing it isn’t v2 — it’s a patch with a loud changelog entry.
The meta-rule: a version is a promise to maintain two contracts forever. Take on that maintenance burden only when the alternative — breaking someone’s production — is worse.
A Versioning Rollout Playbook
Shipping a new version is a program, not a deploy. The sequence that works:
- Freeze v1 semantics. Before v2 exists, decide what v1 means — its behavior is now a spec you test against, not code you refactor. Any change to v1 beyond security patches reopens the “which v1?” question.
- Ship v2 behind the same auth. Don’t make consumers re-onboard — the same API key, the same scopes, a different path. Every credential reset is a migration drop-off point.
- Publish the diff, not the doc. “What changed in v2” — a field-by-field table — converts better than a new reference. Consumers don’t want to re-learn the API; they want to know what breaks them.
- Run the shadow. Use the parallel-run pattern on a traffic slice until mismatches reach zero.
- Deprecate in-band and out-of-band. Headers reach the machines; emails and dashboards reach the humans who decide to migrate. You need both.
- Sunset by data, not by date. The removal day arrives when the usage graph says the remaining traffic is either migrated or consciously abandoned — whichever comes first.
The step everyone skips is 3: most “v2 adoption is slow” complaints trace back to a migration doc that re-teaches the API instead of listing the deltas.
Testing Across Versions
Coexistence is where versioning actually lives or dies — and where test suites go to rot. The rules:
- Contract-test every active version. v1’s tests keep running after v2 ships — that’s the whole point of the version. If v1 tests get deleted because “nobody uses it”, you no longer know what v1 does.
- Test the boundary, not just the versions. The interesting bugs live where versions meet: a v1 client hitting a v2-only field, a middleware that assumes one response shape, a cache key shared across versions.
- Pin versions in tests explicitly. A test that depends on “the default version” fails the day the default moves — write
?version=1or the header into the request, always. - Snapshot the deprecated surface. When you deprecate, capture the current v1 responses as fixtures — they’re the contract you’re promising to keep until sunset. If a refactor changes them, the test catches it before a client does.
Best Practices
- Start with URI path versioning for public APIs — most intuitive for consumers; save exotic strategies for internal services.
- Version at the router level, not per endpoint — consistent versions across the whole API surface.
- Keep old versions running — at least 6 months after the deprecation announcement, longer for public APIs.
- Use semantic versioning for SDKs — major.minor.patch; breaking API changes bump the major.
- Document changes between versions — changelogs are mandatory for public APIs (the api-changelog template covers the format).
- Monitor version usage — don’t remove a version while it still has traffic; let the data set the deadline.
- Prefer additive changes — a new field or endpoint ships on the current version; reserve new versions for breaking changes only.
- Use feature flags for gradual rollout — test new behavior on a traffic percentage before committing.
- Provide migration guides — a step-by-step v1→v2 doc converts more users than any deprecation header.
- Set rate limits lower on old versions — a gentle, honest incentive to migrate.
Common Mistakes
- Not versioning from day one — retrofitting versioning into an API with live clients is painful and always more expensive than doing it upfront.
- Breaking changes without a new version — clients break silently; the version number exists precisely to prevent this.
- Removing old versions too quickly — clients need migration time measured in months, not weeks.
- No deprecation headers — clients discover the removal when their integration breaks, not before.
- Versioning every minor change — additive changes don’t need a new version; that’s how APIs end up on
/v17. - No docs on version differences — consumers guess what changed; a changelog answers it.
- Mixing versioning strategies —
/v2/here,?version=there — pick one and apply it everywhere. - Not testing old versions after deploying new ones — regressions in v1 go unnoticed until a client reports them.
Troubleshooting
- Clients silently getting the wrong version: usually a missing header or unpinned default — check whether the request carried
X-API-Version/?version=, and pin defaults to a fixed version rather than “latest”. - Cache serving mixed versions: the cache key doesn’t include the version — add the header/param to
Varyor the CDN cache key; with path versioning this can’t happen. - 404 after sunset: confirm the old version is actually removed vs the route moved — serve
410 Gonewith a pointer to the migration guide, not a bare 404. - Consumers never saw the deprecation: check that
Deprecation/Sunsetheaders reach them — some proxies strip unknown headers; pair headers with email/docs announcements. - Version-conditional tests failing: pin the test client’s version explicitly — a default version that moves with deploys breaks tests nondeterministically.
See Also
- REST API Design Guide
- GraphQL vs REST
- API Changelog Template
- API Error Handling Guideline
- Recipe: API Versioning
- Companion resources — runnable v1/v2 routers, version middleware, deprecation headers
Further Reading
- IETF Draft — The Deprecation HTTP Header — the header pair this guide implements
- RFC 8594 — The Sunset HTTP Header — the removal-date mechanism
- GraphQL Spec — @deprecated — the schema-evolution primitive
- Stripe API versioning — how a public API versions in practice
Frequently Asked Questions
When should I create a new API version?
Create a new version when you make breaking changes: removing fields, changing field types, changing response structure, changing error codes, or altering authentication. Additive changes — new fields, new endpoints — don't require a new version; ship them on the current one.
Should I version GraphQL APIs?
No — GraphQL is designed for schema evolution. Add fields, deprecate old ones with @deprecated, and make new fields nullable. Only create a new schema for truly incompatible changes, and even then consider running two schemas in parallel behind the same endpoint.
How long should I support old API versions?
Minimum 6 months for internal APIs, 12–24 months for public ones — and let usage decide, not the calendar. Monitor traffic on deprecated endpoints and don't remove a version that still carries real load; a sunset date is a promise you extend, not a timer you obey blindly.
Related Resources
REST API Design Guide
A thorough guide to designing clean, scalable, and maintainable REST APIs.
GuideGraphQL vs REST — When to Choose and How to Migrate
A decision guide comparing GraphQL and REST APIs: use cases, performance, caching, tooling, and migration strategies for engineering teams.
PatternGateway Routing Pattern
Route requests to multiple backend services through a single entry point that handles cross-cutting concerns.
DocAPI Changelog Template
A template for documenting API changes including breaking changes, new features, deprecations, and bug fixes.
DocAPI Error Handling Guideline
A guideline for standardizing error responses, status codes, and error payloads across REST and GraphQL APIs.
RecipeAPI Versioning: URL, Header & Media Type Strategies
How to version REST APIs with URL path, header, and media-type strategies while keeping backward compatibility for existing clients.