Thuta Learning
API Tutorial
AdvancedWeb DevelopmentIntermediate

API Versioning

API TutorialLesson 2735 min

What you'll walk away with

  • Compare URL path, header and media-type versioning with their strengths and weaknesses
  • Classify a change as additive or breaking
  • Choose a safe default (the oldest supported version) for requests that carry no version
  • Add Deprecation, Sunset and Link headers to responses and read them on the client
  • Pin the version explicitly in a client and ignore fields it does not know

Explain it simply

Explain it simply

Think of the editions of a book. When the book is revised and named edition 2 while edition 1 stays on the shelf, a teacher who still teaches from edition 1 does not suddenly find that every page number has moved. An API version works the same way: when the contract has to change, the new shape gets a new name.

The clients of an API are not under your control, and an old app on someone's phone may not update for months. A version tells clients which contract you promise to keep, and it lets you build new things and retire old ones on a timetable.

Problem → Why → Solution

The problem: same URL, different response shape

A mobile app released in March calls GET /users/1 and shows the name field. To tidy the code, the backend team splits name into firstName and lastName, on the same URL. As soon as it is deployed, old copies of the app crash on the profile screen, and users have to wait for an app store update before they can recover.

Nobody wrote a bug on the client. The server quietly broke the contract. You could fix a client you own overnight, but you cannot fix clients that belong to other people.

profile.js
// App released in March: written against the original response
async function showProfile(id) {
  const res = await fetch("https://api.example.com/users/" + id);
  const profile = await res.json();
  // after the backend split "name", profile.name is undefined
  return profile.name.toUpperCase();
}

// TypeError: Cannot read properties of undefined (reading 'toUpperCase')

Why does this happen without a version?

Without a version there is no way to tell the new contract from the old one, so every change reaches every client at the same moment. With versions, old apps keep calling v1 while new ones use v2. When a change is unavoidably breaking, open a new version and give the old one an end date.

Core concept: name the contract, retire it slowly

An API is a contract with programs you cannot see and often cannot ask to update. A mobile app released last spring may still run on thousands of phones, and a partner's nightly integration may not have been touched in two years. If the shape of a response changes under them, they break, and you hear about it from angry users. Versioning means giving each shape of the contract a name, so you can improve the API without surprising anyone who depends on the old one.

There are three common places for the version. In the URL path, as in /v2/users/42, it is the most visible: easy to route, log, cache and try with curl. In a header, such as API-Version: 2 or a date value like Stripe's Stripe-Version, the URLs stay clean but the version is hidden from casual testing. In the media type, as in Accept: application/vnd.example.v2+json, it follows HTTP content negotiation most closely but is the hardest to try in a browser. None is always right. Pick one, use it everywhere, and decide what a request with no version means: the safe answer is the oldest supported contract, never the newest.

Not every change needs a new version. Adding an optional response field is usually compatible, as long as clients ignore fields they do not know. Removing or renaming a field, changing a type, changing what a value means, adding a required request parameter and tightening validation are breaking changes. Subtler changes break clients too: a new enum value that an exhaustive switch does not expect, a different default page size, a changed sort order or a new error format. The test is simple: could a correct, existing client fail? If so, it is a breaking change.

Retiring a version is a process, not a single event. Announce it, then mark every response from the old version with Deprecation and Sunset headers and a Link to the migration guide. Measure which clients still call it, contact the heaviest users directly, and keep contract tests running for every supported version. When the sunset date passes, the endpoint answers 410 Gone instead of quietly returning different data.

Clients have duties as well. Pin the version explicitly in every request instead of trusting a default, log or alert when Deprecation or Sunset headers appear, and read responses tolerantly by ignoring unknown fields. That way the upgrade happens on your schedule, not on the day the old version is switched off.

Mental model: a contract with an end date
  1. Client pins a version
  2. Server routes to that contract
  3. Old version marked Deprecation
  4. Sunset date, then 410 Gone

Every version has a beginning and an end, and clients must be able to see the end coming.

General pattern: where the version goes and how it ends

text
# Pick ONE place for the version and keep it everywhere
URL path:    GET /v2/users/42
Header:      GET /users/42     API-Version: 2
Media type:  GET /users/42     Accept: application/vnd.example.v2+json

# Retiring an old version: say so in every response it sends
Deprecation: @<unix seconds when it was deprecated>
Sunset: <HTTP-date after which it stops working>
Link: <migration guide URL>; rel="deprecation"

The top half shows the three places a version can live; choose just one. The bottom half shows three headers for every response of the old version: when it was deprecated, after which date it stops working, and where to read how to migrate.

Example: URL and media-type versions on one server

In this example one internal model is turned into two public versions by two serializers. v1 has a single name, while v2 splits it into firstName and lastName. The server supports /v1/users/1 and /v2/users/1 (URL versioning) and also /users/1 with Accept: application/vnd.example.v2+json (media-type versioning).

v1 is marked deprecated, so every v1 response carries Deprecation, Sunset and Link headers, and the client prints a warning when it sees them. A request with no version gets v1, because the default is the oldest contract. An unknown version gets 404 on the URL form and 406 Not Acceptable on the Accept form.

versions.mjs
import http from "node:http";

// One internal model, two public representations of it.
const user = { id: 1, firstName: "Aye", lastName: "Chan" };
const representations = {
  1: (u) => ({ id: u.id, name: u.firstName + " " + u.lastName }),
  2: (u) => ({ id: u.id, firstName: u.firstName, lastName: u.lastName }),
};
const DEPRECATED = {
  1: { since: "@1767225600", sunset: "Fri, 15 Jan 2027 00:00:00 GMT" },
};

function send(res, version, via) {
  const render = representations[version];
  if (!render) {
    res.writeHead(via === "path" ? 404 : 406, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ error: "unsupported_version" }));
    return;
  }
  const headers = { "Content-Type": "application/vnd.example.v" + version + "+json" };
  if (via === "media-type") headers.Vary = "Accept";
  const info = DEPRECATED[version];
  if (info) {
    headers.Deprecation = info.since;
    headers.Sunset = info.sunset;
    headers.Link = '<https://api.example.com/docs/migrate-to-v2>; rel="deprecation"';
  }
  res.writeHead(200, headers);
  res.end(JSON.stringify(render(user)));
}

const server = http.createServer((req, res) => {
  const byPath = req.url.match(/^\/v(\d+)\/users\/1$/);
  if (byPath) return send(res, Number(byPath[1]), "path");
  if (req.url === "/users/1") {
    const accept = req.headers.accept ?? "";
    const wanted = accept.match(/application\/vnd\.example\.v(\d+)\+json/);
    const version = wanted ? Number(wanted[1]) : 1; // default: the oldest contract
    return send(res, version, "media-type");
  }
  res.writeHead(404).end();
});

await new Promise((resolve) => server.listen(0, resolve));
const base = "http://127.0.0.1:" + server.address().port;

async function get(label, path, accept) {
  const res = await fetch(base + path, accept ? { headers: { Accept: accept } } : {});
  console.log(label + ": " + res.status + " " + (await res.text()));
  if (res.status === 200) {
    console.log("  content-type: " + res.headers.get("content-type"));
  }
  if (res.headers.has("deprecation")) {
    console.log("  warning: deprecated, sunset " + res.headers.get("sunset"));
  }
}

await get("URL v1", "/v1/users/1");
await get("URL v2", "/v2/users/1");
await get("URL v9", "/v9/users/1");
await get("Accept v2", "/users/1", "application/vnd.example.v2+json");
await get("no version", "/users/1");
await get("Accept v9", "/users/1", "application/vnd.example.v9+json");
server.close();

Code breakdown

  1. One modelconst user = { id: 1, firstName: "Aye", lastName: "Chan" };

    The server has a single data model. Instead of copying the model per version, only the response shape is versioned, which keeps maintenance simple.

  2. v1 serializer1: (u) => ({ id: u.id, name: u.firstName + " " + u.lastName }),

    The v1 contract has one name, so this serializer joins firstName and lastName back together. The internal model can change and old apps keep working.

  3. URL versionconst byPath = req.url.match(/^\/v(\d+)\/users\/1$/);

    A regular expression reads the number after v in the path. Only /users/1 is routed to keep the example short; a real router would use a parameter such as /v:version/users/:id.

  4. Safe defaultconst version = wanted ? Number(wanted[1]) : 1;

    With no version in the Accept header, it picks 1. Defaulting to the latest version would instantly break old clients that predate version headers, so the oldest contract is the safe choice.

  5. Deprecation signalheaders.Deprecation = info.since;

    Every response from the old version says when it was deprecated, and Sunset and Link follow. The client reads these headers and prints a warning.

  6. Varyif (via === "media-type") headers.Vary = "Accept";

    With media-type versioning the same URL returns different bodies depending on Accept, so Vary: Accept stops a cache from handing a v1 response to a v2 caller.

You should see
URL v1: 200 {"id":1,"name":"Aye Chan"}
  content-type: application/vnd.example.v1+json
  warning: deprecated, sunset Fri, 15 Jan 2027 00:00:00 GMT
URL v2: 200 {"id":1,"firstName":"Aye","lastName":"Chan"}
  content-type: application/vnd.example.v2+json
URL v9: 404 {"error":"unsupported_version"}
Accept v2: 200 {"id":1,"firstName":"Aye","lastName":"Chan"}
  content-type: application/vnd.example.v2+json
no version: 200 {"id":1,"name":"Aye Chan"}
  content-type: application/vnd.example.v1+json
  warning: deprecated, sunset Fri, 15 Jan 2027 00:00:00 GMT
Accept v9: 406 {"error":"unsupported_version"}

Comparing versioning strategies

StrategyExampleMain trade-off
URL path/v2/users/42Visible and easy to try, but URLs multiply
Custom headerAPI-Version: 2Clean URLs, but easy to forget or miss
Media typeAccept: ...v2+jsonClosest to HTTP, but harder tooling
Query parameter/users/42?version=2Simple, but muddles cache keys

Whichever you choose, apply it everywhere; using more than one confuses clients. Some providers keep the major version in the URL and use a dated header for smaller changes, and the GitHub REST API, for example, selects its version with the X-GitHub-Api-Version header. Check the provider's own documentation for its current rules.

Checking additive versus breaking mechanically

Changes do not have to be judged by eye alone. The function below compares response field names and types, treating a removed field or a changed type as breaking and a new field as additive. It sees only structure, so it cannot notice behavioural changes such as a new enum value or a different default; reviews and tests have to catch those. Tools that compare two OpenAPI documents apply the same idea more thoroughly.

diff-contracts.mjs
function diffContracts(before, after) {
  const breaking = [];
  const additive = [];
  for (const [field, type] of Object.entries(before)) {
    if (!(field in after)) breaking.push(field + " removed");
    else if (after[field] !== type) {
      breaking.push(field + " changed from " + type + " to " + after[field]);
    }
  }
  for (const field of Object.keys(after)) {
    if (!(field in before)) additive.push(field + " added");
  }
  return { breaking, additive };
}

const v1 = { id: "number", name: "string" };
const candidates = {
  "v1 + avatarUrl": { id: "number", name: "string", avatarUrl: "string" },
  "v1 with string id": { id: "string", name: "string" },
  "v1 split name": { id: "number", firstName: "string", lastName: "string" },
};

for (const [label, shape] of Object.entries(candidates)) {
  const { breaking, additive } = diffContracts(v1, shape);
  const verdict = breaking.length ? "needs a new version" : "safe to ship in v1";
  console.log(label);
  if (breaking.length) console.log("  breaking: " + breaking.join(", "));
  if (additive.length) console.log("  additive: " + additive.join(", "));
  console.log("  verdict: " + verdict);
}
text
v1 + avatarUrl
  additive: avatarUrl added
  verdict: safe to ship in v1
v1 with string id
  breaking: id changed from number to string
  verdict: needs a new version
v1 split name
  breaking: name removed
  additive: firstName added, lastName added
  verdict: needs a new version

The steps for retiring a version

1. Announce it and set a date

Announce it in the changelog, by email and on a dashboard, and state the sunset date plainly. Give clients months, and for some audiences a year, to move.

2. Add headers to every response

The Deprecation header says when the version was deprecated and, in current specifications, is written as @ followed by Unix seconds (older APIs send Deprecation: true). Sunset (RFC 8594) gives the HTTP-date after which it stops working, and Link with rel="deprecation" points at the migration guide.

3. Measure who still calls it

Log request counts per version and per API key. Close to the deadline you can contact the remaining callers directly.

4. Brownouts, then the sunset

A brownout is a deliberate, short shutdown of the old version that wakes up callers who ignored the announcements. When the sunset date arrives, return 410 Gone.

text
HTTP/1.1 200 OK
Content-Type: application/vnd.example.v1+json
Deprecation: @1767225600
Sunset: Fri, 15 Jan 2027 00:00:00 GMT
Link: <https://api.example.com/docs/migrate-to-v2>; rel="deprecation"

To look at it yourself, call the API with curl and an Accept header and read the response headers. If your client code also watches for these headers, you get a warning long before the old version is switched off.

bash
curl -i https://api.example.com/users/1 \
  -H "Accept: application/vnd.example.v1+json"

In real projects

Where this shows up in real projects

For mobile apps versioning is unavoidable, because app store review means not every user updates at the same moment. Some providers, payment platforms for instance, pin each account to a dated version and let the owner move forward when ready. The pattern helps internal APIs too: when two teams cannot deploy at the same instant, two versions can run side by side.

In a project that moves a user schema from v1 to v2, write a compatibility table (what happens to every field), put a v1 adapter on top of the v2 model, publish the migration timeline and run consumer contract tests in CI. If every request log records the version, "who still uses v1?" becomes a single query. Keep one OpenAPI document per version and, as the next lesson shows, add a breaking-change diff to CI.

Common mistakes

Common mistakes

1. Changing the contract in place with no version

"We are the only client" is rarely true, so do not rename a field or change a type in place. Old apps, caches and other teams' scripts are still out there. A breaking change needs a new version.

2. Assuming an added field is always safe

Some clients validate responses with a strict schema and reject unknown fields, and an exhaustive switch fails on a new enum value. Write clients that ignore unknown fields, and treat a new enum value on your side with care.

3. Defaulting unversioned requests to the latest

Clients that predate your version header send none, so defaulting to the latest breaks all of them the day v3 ships. Default to the oldest supported contract, or reject plainly with a 400.

4. Switching a version off without usage data

Announcing and then switching off on the date abruptly breaks the clients who never read the notice. Warn with per-version logs, the Deprecation header and brownouts, and extend the date if heavy users remain.

Best practices

Best practices

  • Keep additive changes inside one version and open a new one only for a real breaking change, so the number of versions does not multiply.
  • Expose one internal model through per-version serializers instead of copying business logic for every version.
  • On the client, pin the version in a single constant and feed Deprecation and Sunset headers into your logging.

Mini challenge

Mini challenge: choosing a version from Accept

Write parseAcceptVersion(accept, supported, fallback). The Accept header may list application/vnd.example.vN+json media types with q values. Starting from the most preferred (highest q), return a supported version; application/json and */* yield the fallback; return null when nothing matches (the server would send 406).

  • Return the fallback when there is no Accept header
  • Split on commas, read q (default 1) and try the ranges from highest q, keeping the written order on ties
  • Skip q=0, return a supported vnd.example.vN+json version, and skip unsupported ones
  • application/json and */* return the fallback; return null when nothing matches
  • Print seven examples using supported = [1, 2] and fallback = 1
accept-version.mjs
// Pick an API version from an Accept header such as
//   "application/vnd.example.v3+json, application/vnd.example.v2+json;q=0.8"
// Return a supported version, the fallback, or null (the server would answer 406).

function parseAcceptVersion(accept, supported, fallback) {
  // TODO 1: no Accept header at all -> return fallback
  // TODO 2: split on commas and read each media type with its q value (default 1)
  // TODO 3: order the ranges by q, highest first, keeping the written order on ties
  // TODO 4: skip q=0; return the number from a supported application/vnd.example.vN+json
  // TODO 5: application/json and */* mean "any contract": return fallback
  // TODO 6: nothing acceptable -> return null
}

// TODO: with supported = [1, 2] and fallback = 1, print the result for seven values

Expected: The seven results are 1, 2, 2, 1, null, null, 1: (no Accept header) -> 1 application/vnd.example.v2+json -> 2 application/vnd.example.v3+json, application/vnd.example.v2+json;q=0.8 -> 2 application/json -> 1 application/vnd.example.v9+json -> null text/html -> null application/vnd.example.v2+json;q=0, application/json -> 1

Show hint

Split each part again on ";" and read q=... with a regular expression. Sort by q first and by the original index on ties. When a version is unsupported, continue the loop instead of returning.

Show solution
accept-version.mjs
const MEDIA = /^application\/vnd\.example\.v(\d+)\+json$/;

function parseAcceptVersion(accept, supported, fallback) {
  if (!accept) return fallback;
  const ranges = accept.split(",").map((part, index) => {
    const [type, ...params] = part.split(";").map((piece) => piece.trim());
    const q = params.map((param) => param.match(/^q=([0-9.]+)$/)).find(Boolean);
    return { type: type.toLowerCase(), q: q ? Number(q[1]) : 1, index };
  });
  ranges.sort((a, b) => b.q - a.q || a.index - b.index);

  for (const { type, q } of ranges) {
    if (q === 0) continue;
    const match = type.match(MEDIA);
    if (match) {
      const version = Number(match[1]);
      if (supported.includes(version)) return version;
    } else if (type === "application/json" || type === "*/*") {
      return fallback;
    }
  }
  return null;
}

const supported = [1, 2];
const cases = [
  undefined,
  "application/vnd.example.v2+json",
  "application/vnd.example.v3+json, application/vnd.example.v2+json;q=0.8",
  "application/json",
  "application/vnd.example.v9+json",
  "text/html",
  "application/vnd.example.v2+json;q=0, application/json",
];
for (const accept of cases) {
  const shown = accept ?? "(no Accept header)";
  console.log(shown.padEnd(72) + " -> " + parseAcceptVersion(accept, supported, 1));
}

Quick quiz 1 / 3

Which change can ship inside v1 without opening a new version?

Quick quiz 2 / 3

An old client that predates version headers calls GET /users/1 with no version information. Which default protects it?

Quick quiz 3 / 3

What does a Sunset: Fri, 15 Jan 2027 00:00:00 GMT response header tell a client?

What to remember

  • A version names a contract: choose URL path, header or media type, use it everywhere, and default unversioned requests to the oldest supported contract.
  • Adding an optional field is additive; removing a field, changing a type, a new required parameter or a changed error format are usually breaking.
  • Retire an old version with Deprecation, Sunset (an HTTP-date) and Link headers, usage measurement and brownouts, then return 410 Gone after the date.
  • Clients pin the version, watch for Deprecation and Sunset headers, and ignore fields they do not know.

OpenAPI Specification — OpenAPI Initiative

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

API Versioning | Thuta Learning