1. Home
  2. Blog
  3. Software Development

Software Development

API Versioning: URL vs Header vs Media Type, With Deprecation

API versioning lets you change an API without breaking the apps that already depend on it. Learn what counts as a breaking change, the four common versioning strategies with their trade-offs, how to deprecate and sunset old versions with standard headers, and how to test it all, with a local server we ran.

9 min read
API versioning: URL vs header vs media type, with deprecation

Key takeaways

  • API versioning is only needed for breaking changes; additive changes can ship in place.
  • URL versioning (/v1/users) is the most common and easiest to test and cache; header and media type versioning keep URLs stable.
  • Announce the end of a version with Deprecation, Sunset and a Link to its successor, as our test server did.
  • Our version 1 client crashed with AttributeError on a version 2 payload, the exact failure versioning prevents.

An API is a promise. Mobile apps in users’ pockets, partner integrations and internal services all rely on the exact shape of your responses. Change a field name and some of them break, often in apps you cannot update. API versioning lets you evolve the API while old clients keep working until they are ready to move.

To make the strategies concrete, we built a small Python server (Python 3.13.6, standard library only) that serves two versions of a user resource and selects the version four different ways. Every response below is from that run. For general API design, see our REST API best practices.

What is API versioning?

API versioning means giving each incompatible revision of an API contract its own identifier, so clients can say which one they expect. The server keeps serving older versions for a while, and clients migrate on their own schedule. The version is a contract number, not your release number: a server can ship many releases a week while the API stays at version 2.

Breaking vs non-breaking changes

Usually safe (no new version) Breaking (needs a new version)
Adding a new endpoint Removing or renaming an endpoint or field
Adding an optional request field Making an optional field required
Adding a field to a response Changing a field’s type or structure
Adding a new enum value clients can ignore Changing the meaning of a value or default
Performance improvements Changing status codes or error formats clients rely on

“Safe” assumes clients follow the tolerant-reader rule: ignore unknown fields and do not depend on field order. Strict clients that reject unknown fields can break even on additions, so document that rule for your consumers.

A breaking change in action

Our version 1 returned the name as one string. Version 2 split it into parts and moved the email into a contact object:

GET /v1/users/7
{"id": 7, "name": "Asha Rao", "email": "asha@example.com"}

GET /v2/users/7
{"id": 7, "name": {"first": "Asha", "last": "Rao"},
 "contact": {"email": "asha@example.com"}}

A client written for version 1 that receives the version 2 payload fails immediately:

old_client["name"].upper()
# AttributeError: 'dict' object has no attribute 'upper'

Same URL resource, same user, different shape. Without versioning, every deployed client would crash the moment version 2 shipped. Consumer-driven contract tests catch this kind of change before it reaches production.

Four API versioning strategies

Our server accepted the version in four ways, and every request returned the version 2 shape:

GET /v2/users/7                                        -> via url
GET /users/7      API-Version: 2                       -> via header
GET /users/7      Accept: application/vnd.shop.v2+json -> via media type
GET /users/7?version=2                                 -> via query

Each response also carried an API-Version: 2 header confirming which version was served, a small courtesy that makes debugging much easier.

1. URL path versioning

The version is part of the path: /v1/users, /v2/users. It is by far the most widely used approach.

  • Pros: visible in logs and browser bars, trivial to test with curl, easy to route in gateways, and cacheable by CDNs without special rules.
  • Cons: the same resource has several URLs; purists argue a resource identifier should not change when its representation changes.

The client sends a header such as API-Version: 2 and the URL stays /users/7. Some public APIs use a date instead of a number, for example a version string like 2026-11-01, which pins a client to the API as it existed on that day.

  • Pros: clean, stable URLs; easy to make a header required.
  • Cons: invisible in a URL, so harder to test in a browser and to share; caches must vary on the header.

3. Media type (content negotiation)

The version lives in the Accept header as a vendor media type, such as application/vnd.shop.v2+json. It follows HTTP content negotiation most closely, since a version is really a different representation of the same resource.

  • Pros: most RESTful; can version individual resources independently.
  • Cons: most complex for clients and tooling; easy to get the header slightly wrong.

4. Query parameter

/users/7?version=2 is simple and visible, but query strings are often treated as optional filters, can be dropped by proxies or link builders, and mix versioning with other parameters. It works for quick internal APIs; most public API guides prefer one of the other three.

API versioning strategies compared

Strategy Visibility Caching Ease for clients REST purity
URL path High Simple Easiest Lower
Custom header Low Needs Vary Medium Medium
Media type Low Needs Vary Hardest Highest
Query parameter High Simple Easy Low

For most teams, URL versioning is the pragmatic default. Whichever you choose, use it consistently across the whole API. When the version comes from a header, send Vary: Accept, API-Version, as our server did, so caches do not serve one version’s response to another version’s client; our HTTP caching guide explains Vary.

The default version question

GET /users/7          (no version given)
-> via default, version 1 payload, with Deprecation headers

Our server fell back to version 1 when no version was given, the conservative choice that keeps old clients working. The alternative, defaulting to the latest version, breaks unversioned clients every time you release. Many API designers recommend making the version mandatory instead, rejecting unversioned requests with a clear error, so nobody depends on a moving default.

GET /v3/users/7
-> 400 {"error": "unsupported version 3", "supported": ["1", "2"]}

An unknown version should fail loudly with the list of supported versions. Our server returned 400; 404 is also common for URL versioning. See the HTTP status codes cheat sheet.

Deprecating and sunsetting old versions

GET /v1/users/7
API-Version: 1
Deprecation: true
Sunset: Wed, 30 Jun 2027 23:59:59 GMT
Link: </v2/users/7>; rel="successor-version"

Version 1 responses carried three standard signals. Sunset (RFC 8594) gives the date the version will stop working. Deprecation, standardised in RFC 9745 in 2025, says the version is deprecated; the RFC’s preferred value is a date, while true is the widely used older draft form. Link with rel="successor-version" points clients to the replacement. Pair the headers with human communication:

  1. Announce the new version and a migration guide.
  2. Add deprecation headers to the old version and log which clients still call it.
  3. Contact the remaining heavy users directly.
  4. Run brownouts: short planned outages of the old version to flush out forgotten clients.
  5. Retire it on the sunset date, returning 410 Gone with a pointer to the new version.

Tip: measure usage per version and per client key before choosing a sunset date. Six to twelve months of overlap is common for public APIs.

Implementation tips

  • Keep one domain model and map it to each version’s shape in a thin layer, as our v1() and v2() view functions did, instead of duplicating business logic.
  • Version the whole API, not individual fields, unless you deliberately choose media type versioning per resource.
  • Use major versions only (v1, v2); additive changes do not need v1.1. This mirrors the major number in semantic versioning.
  • Publish an OpenAPI document per version and a changelog that marks breaking changes.
  • Route versions at the gateway when they live in separate services.

Testing a versioned API

  • Run the full suite against every supported version, not just the newest.
  • Keep snapshot or contract tests of each version’s response shape.
  • Assert the API-Version, Deprecation and Sunset headers.
  • Test unversioned and unknown-version requests.
  • Check that caching varies correctly when using header versioning.

Our API testing with Python guide shows how to automate such checks.

Avoiding new versions in the first place

The best version is the one you never need. Design responses for growth (objects instead of bare strings when more detail is likely), add fields instead of changing them, use feature flags for gradual rollouts, and accept new optional parameters for new behaviour. Some teams choose an evolving API like GraphQL, which deprecates fields rather than versioning the whole API; see REST vs GraphQL.

Final thoughts

API versioning is about trust: clients can upgrade when they are ready, and you can still improve the API. Version only for breaking changes, pick one strategy (URL versioning is a sound default), serve a clear version header, reject unknown versions loudly, and retire old versions with Deprecation, Sunset and successor links plus plenty of notice. Do that, and a breaking change becomes a planned migration instead of an outage.

Frequently asked questions

What is API versioning?

It is the practice of giving each incompatible revision of an API its own version identifier, so existing clients keep working while new clients adopt the changed contract.

What is the best API versioning strategy?

For most teams URL path versioning, such as v1 and v2 in the path, is the best default because it is visible, easy to test and simple to cache. Header or media type versioning suits teams that want stable URLs.

When should I create a new API version?

Only for breaking changes, such as removing or renaming fields, changing types or making optional fields required. Adding new optional fields or endpoints usually does not need a new version.

How do I deprecate an old API version?

Announce the change, add Deprecation and Sunset headers plus a successor Link to old responses, track which clients still use it, contact them, and retire it on the published date.

Should the API version be in the URL or a header?

Both work. The URL is easier to see, share, test and cache. A header keeps resource URLs stable but needs Vary headers for caching and is harder to try in a browser.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
Software Development

301 vs 302 Redirect: Differences, SEO Impact, 307 and 308

301 vs 302 redirect: the differences, SEO impact, 307 and 308, method changes, redirect chains and loops, all tested on…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Databases & SQL

SQL Random Rows: How to Select Random Rows Fast and Fairly

SQL random rows: how to select random rows fast and fairly, timing ORDER BY RANDOM, offsets and ID jumps, and…

Read article →
Databases & SQL

SQL Median: 4 Ways to Calculate the Median, With Tested Queries

SQL median explained: four tested ways to calculate the median, including percentile functions, window ranks, offsets and per group medians.

Read article →
Software Development

JavaScript Regex Explained: Patterns, Flags, Groups and Pitfalls

JavaScript regex explained: literals, flags, groups, named groups, lookarounds, matchAll, replace and the catastrophic backtracking trap, tested in Node.

Read article →
Software Development

Python property: Getters, Setters, Validation and cached_property

Python property explained: getters, setters, deleters, validation, read-only and computed attributes, and cached_property, with tested code.

Read article →
Software Development

Python Enum Explained: auto, IntEnum, StrEnum, Flag and Best Practices

Python enum explained with tested examples: Enum, auto, IntEnum, StrEnum, Flag, aliases, unique, JSON serialisation and match statements.

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
Software Development

401 vs 403: Unauthorized vs Forbidden, and When to Use Each

401 vs 403 explained: authentication vs authorization, the WWW-Authenticate header, when to return 404 instead, client reactions and a tested…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →
Databases & SQL

SQL ROUND Function: Decimals, Ties, CEIL, FLOOR and Money

SQL ROUND explained with tested queries: decimals, tie rules, the 2.675 float trap, negative digits, CEIL, FLOOR, truncation and rounding…

Read article →
Databases & SQL

Recursive CTE in SQL: Hierarchies, Paths, Series and Cycles

Recursive CTE in SQL explained with tested queries: org charts with levels and paths, walking up a tree, team sizes,…

Read article →
Software Development

JavaScript Deep Copy: structuredClone vs JSON vs Spread, Tested

JavaScript deep copy compared: spread, Object.assign, the JSON trick, structuredClone and a custom copy, tested on Dates, Maps, Sets, BigInt…

Read article →
Artificial Intelligence

K Means Clustering Explained: How It Works, With Python Code

K means clustering explained: the algorithm, a from-scratch NumPy version, choosing k with the elbow and silhouette methods, k-means++, scaling…

Read article →
DevOps

Git Log Explained: 15 Useful Commands and Pretty Formats

Git log explained with 15 tested commands: oneline, graph, filters by author, date, message and code, file history, stats, pretty…

Read article →
Test Automation

Pytest conftest.py Explained: Shared Fixtures, Hooks and Overrides

Pytest conftest.py explained with a tested suite: shared fixtures, scope and teardown, folder overrides, autouse, custom options, markers and useful…

Read article →
Software Testing

Usability Testing: Methods, Metrics, SUS Score and Checklist

Usability testing explained: methods, planning, writing tasks, running sessions, metrics, SUS scoring, how many users you need and a practical…

Read article →
Databases & SQL

SQL UPDATE Statement: Safe Updates, UPDATE With JOIN and RETURNING

The SQL UPDATE statement explained with tested examples: WHERE guards, CASE updates, UPDATE with JOIN, the subquery NULL trap, RETURNING…

Read article →
Databases & SQL

SQL COUNT: COUNT(*) vs COUNT(column) vs COUNT(DISTINCT) Explained

SQL COUNT explained: COUNT(*) vs COUNT(column) vs COUNT(DISTINCT), NULLs and empty strings, conditional counts, HAVING, the LEFT JOIN trap and…

Read article →
Artificial Intelligence

K Nearest Neighbors (KNN) Explained: How It Works, With Python Code

K nearest neighbors explained: the KNN algorithm, a from-scratch NumPy version, choosing k, feature scaling, distance metrics, regression and vector…

Read article →
DevOps

Git Rebase Interactive: Squash, Fixup, Reword and Autosquash

Git rebase interactive explained step by step: pick, reword, squash, fixup, edit, drop, autosquash, conflicts and undoing a rebase with…

Read article →
Software Testing

Alpha vs Beta Testing: Key Differences, Exit Criteria and Checklist

Alpha vs beta testing compared: who tests, what each phase finds, entry and exit criteria, how to run a beta,…

Read article →
Test Automation

Pytest Monkeypatch: 10 Tested Examples for Env Vars, Time and APIs

Pytest monkeypatch explained with 10 passing tests: environment variables, functions, config, time, sleeps, paths, blocking the network and the wrong-target…

Read article →
Artificial Intelligence

Softmax Function Explained: Formula, Python Code and Stable Version

The softmax function explained: formula, worked example, NumPy code, the stable version that avoids NaN, temperature, cross-entropy and softmax vs…

Read article →
DevOps

Git Diff Explained: Staged Changes, Branches and Commits

Git diff explained: read the output, compare unstaged and staged changes, commits and branches, two dots vs three dots, and…

Read article →
Test Automation

Pytest Xdist: Run Tests in Parallel and Cut Test Time

Run pytest tests in parallel with pytest-xdist: install, the -n option, distribution modes, real timings and how to fix shared-state…

Read article →
Software Testing

Verification vs Validation in Software Testing: Example and Table

Verification vs validation in software testing explained with a comparison table and a tested coupon example where every spec test…

Read article →
Artificial Intelligence

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →