Part 03 · The Language of the Web

API Versioning and Compatibility

VersioningAPI

Changing an API without breaking the apps that already depend on it.

⏱ 1 hours · Station 39 of 153

A one-word rename that crashed the app

A backend developer tidies up the user API: name becomes full_name, because it reads better next to the new display_name. Tests pass, the web frontend is updated in the same pull request, and the deploy goes out on Thursday evening.

On Friday morning the support inbox is full. The Android app, version 3.2, which 60% of users haven't updated, reads user.name, gets nothing, and crashes on the profile screen. The fix isn't "release a new app": that takes days to get through store review, and many people never update at all. The only fast fix is to put name back.

A web page is downloaded fresh on every visit. A mobile app, a partner's integration or another team's service is code you don't control, running old versions for months or years. Once someone depends on your API, its responses are a contract. This lesson is about changing an API without breaking that contract: which changes are safe, how to ship the ones that aren't as a new version, and how to retire old versions politely.

The problem: you can't update your clients

ChangeExampleOld clients
Add an optional field to a responseadd emailfine, if they ignore unknown fields
Add a new endpointGET /users/42/badgesfine, they never call it
Add an optional request parameter?include=ordersfine, they don't send it
Remove or rename a response fieldname → full_namebroken
Change a type or format"price": "500" → "price": 500broken
Make an optional request field requiredphone now requiredbroken: their requests start failing
Change meaningamount in taka → in paisasilently broken: worst kind

The top three are backward-compatible (additive). The rest are breaking. The whole art of API evolution is doing as much as possible with additive changes, and putting the unavoidable breaking ones behind a new version.

Think of a wall socket

Bangladesh's wall sockets have accepted the same plugs for decades. Manufacturers keep making better fans and phone chargers, but nobody ships a fan with a new plug shape and expects every house to rewire.

  • Additive change is a socket that also gets a USB port. Old plugs still fit; new devices can use the extra port.
  • Breaking change is a new plug shape. If you must do it, you don't rip out the old sockets: you install the new kind next to them, sell adapters, and announce years ahead that the old kind will be phased out.
  • Versioning is exactly that: /v1 sockets keep working while /v2 is installed beside them.
two versions, one coreold appreads namenew appreads first_name/v1 adapterjoins the name/v2 adaptercore userfirst + lastGETreadnameGETreadfirst, lastafter the sunset date: /v1 answers 410 Gone
An old app calls /v1 and gets "name"; a new app calls /v2 and gets first_name and last_name. Both version adapters read the same core user record, which stores first and last name. Later, after the sunset date, /v1 answers 410 Gone.

Where the analogy stops working. Old sockets cost nothing to keep. Every live API version costs you: code paths to maintain, tests to run, bugs to fix twice. That's why versions need a planned end, and why you avoid creating them for changes that could have been additive.

The building blocks

  1. Your responses are a contract. Field names, types, formats, status codes, error shapes and meanings. Anything a client can observe, someone may depend on (Hyrum's law).
  2. Prefer additive changes. New optional fields, new endpoints, new optional parameters and new enum values (if clients were told to expect them). These need no new version.
  3. Clients must be tolerant readers. Ignore fields you don't know; don't fail on them. Read only what you need. A strict client that rejects unknown fields turns every additive change into a breaking one.
  4. Servers should be careful writers. Never remove, rename or retype a field inside a version. Keep defaults stable. Document which enums may grow.
  5. When you must break, make a new version. Common styles:
    • Path: /v1/users, /v2/users. Most visible, easy to route and cache, easy to test with curl.
    • Header: API-Version: 2 or a date like X-GitHub-Api-Version: 2022-11-28. Clean URLs; easy to forget.
    • Date-pinned (Stripe style): each account is pinned to the version it started on, and upgrades explicitly. Pick one style and use it everywhere.
  6. Versions are thin adapters over one core. Keep one domain model and database. Each version is a small layer that maps the core to its own representation (v1 joins first and last name into name). Never fork the whole codebase per version.
  7. Unversioned requests need a fixed default. If a request has no version, it gets the oldest supported version (or the account's pinned one), never "latest", or every release silently breaks old clients.
  8. Deprecate, then sunset. Announce early, add Deprecation and Sunset response headers (RFC 9745 and RFC 8594) to the old version, measure who still calls it, contact them, and only then turn it off, ideally returning 410 Gone with a link to the migration guide.
Predict first

v1 of an API returns {"status": "paid"} with values pending, paid and refunded. The team wants to add a new status, partially_refunded. Is that a breaking change?

Behind the scenes: retiring v1

Step through it

From launching v2 to switching off v1

API teamv1v2Clients

Step 1/5 v2 ships next to v1

The breaking change (splitting name into first_name and last_name) goes only into /v2. /v1 keeps returning name, built by an adapter from the same core record.

live
v1, v2

The picture to keep in your head

An API is a promise with a version number on it.

  • Inside a version: only add, never take away or change meaning.
  • Clients read tolerantly: take what they need, ignore the rest.
  • A breaking change gets a new version, built as a thin adapter over the same core, running side by side with the old one.
  • Old versions end on a date: deprecate loudly, measure, help people move, then sunset.

Try it: breaking or safe?

Try each case

Can this ship without a new version?

new optional field
works: Additive. Tolerant clients ignore it; new clients can use it.

Code from first principles

A server that serves user 42 in two versions: v1 with a single name, v2 with first_name and last_name. Requests without a version get v1, unknown versions are rejected, and v1 responses carry deprecation headers. Then an old app that only reads name is run against an additive change, an in-place rename and v2, first as a tolerant reader and then as a strict one.

package main

import (
	"fmt"
	"strings"
)

// A field is a name and its value already written as JSON.
type field struct{ k, v string }

func obj(fs []field) string {
	parts := []string{}
	for _, f := range fs {
		parts = append(parts, `"`+f.k+`":`+f.v)
	}
	return "{" + strings.Join(parts, ",") + "}"
}

// user returns user 42 as a given version of the API represents it.
// change simulates edits to v1: "email added" (additive) or "name renamed" (breaking).
func user(version, change string) []field {
	if version == "v2" { // v2 splits the name; that's why it's a new version
		return []field{{"id", "42"}, {"first_name", `"Rahim"`}, {"last_name", `"Uddin"`}}
	}
	fs := []field{{"id", "42"}, {"name", `"Rahim Uddin"`}}
	if change == "email added" {
		fs = append(fs, field{"email", `"[email protected]"`})
	}
	if change == "name renamed" {
		fs[1].k = "full_name"
	}
	return fs
}

// The server picks the version from the path. No version means v1, and that default never changes.
func get(path string) string {
	parts := strings.Split(strings.Trim(path, "/"), "/")
	version := "v1"
	if len(parts[0]) > 1 && parts[0][0] == 'v' && parts[0][1] >= '0' && parts[0][1] <= '9' { // "v2", not "videos"
		version = parts[0]
	}
	switch version {
	case "v1":
		note := "  Deprecation: true, Sunset: 2027-06-30"
		if !strings.HasPrefix(path, "/v1") {
			note = "  (no version: v1)"
		}
		return "200 " + obj(user("v1", "")) + note
	case "v2":
		return "200 " + obj(user("v2", ""))
	}
	return `400 {"error":"unknown version ` + version + `, supported: v1, v2"}`
}

// The old mobile app reads only "name". A tolerant reader ignores fields it doesn't know;
// a strict one rejects them.
func oldApp(fs []field, strict bool) string {
	name := ""
	for _, f := range fs {
		switch f.k {
		case "id":
		case "name":
			name = strings.Trim(f.v, `"`)
		default:
			if strict {
				return "broken: unknown field " + f.k
			}
		}
	}
	if name == "" {
		return "broken: missing field name"
	}
	return "ok: " + name
}

func main() {
	for _, p := range []string{"/v1/users/42", "/v2/users/42", "/users/42", "/v9/users/42"} {
		fmt.Printf("GET %-13s -> %s\n", p, get(p))
	}
	cases := []struct{ label, version, change string }{
		{"v1 as it is", "v1", ""},
		{"v1 + email added", "v1", "email added"},
		{"v1 name renamed", "v1", "name renamed"},
		{"v2", "v2", ""},
	}
	fmt.Println("old app (reads name), tolerant reader:")
	for _, c := range cases {
		fmt.Printf("  %-17s -> %s\n", c.label, oldApp(user(c.version, c.change), false))
	}
	fmt.Println("old app (reads name), strict reader:")
	fmt.Printf("  %-17s -> %s\n", "v1 + email added", oldApp(user("v1", "email added"), true))
}

Output (the same in all five languages):

GET /v1/users/42  -> 200 {"id":42,"name":"Rahim Uddin"}  Deprecation: true, Sunset: 2027-06-30
GET /v2/users/42  -> 200 {"id":42,"first_name":"Rahim","last_name":"Uddin"}
GET /users/42     -> 200 {"id":42,"name":"Rahim Uddin"}  (no version: v1)
GET /v9/users/42  -> 400 {"error":"unknown version v9, supported: v1, v2"}
old app (reads name), tolerant reader:
  v1 as it is       -> ok: Rahim Uddin
  v1 + email added  -> ok: Rahim Uddin
  v1 name renamed   -> broken: missing field name
  v2                -> broken: missing field name
old app (reads name), strict reader:
  v1 + email added  -> broken: unknown field email

Reading the output:

  • /v1 and /v2 live side by side, built from the same core user. v1 carries Deprecation and Sunset, so clients and their monitoring can see it's going away and when.
  • No version means v1: the default is fixed, so an old client that never sent a version keeps getting what it always got.
  • An unknown version is a clear 400 that lists the supported ones, instead of silently falling back to something else.
  • Adding email didn't break the tolerant old app: it read name and ignored the rest. That's why additive changes don't need a new version.
  • Renaming in place broke it (missing field name), exactly like the Android app in the story. And pointing the old app at v2 breaks it too, which is fine: v2 is opt-in.
  • The strict reader broke on a purely additive change (unknown field email). Client-side strictness turns safe changes into outages. Tolerant reading is half of the compatibility deal.

A real retirement: Docker Hub's image registry.

$ for p in /v2/ /v1/_ping; do curl -s -o /dev/null -w "GET $p -> %{http_code}\n" https://registry-1.docker.io$p; done
GET /v2/ -> 401
GET /v1/_ping -> 404
$ curl -s -o /dev/null -D - https://registry-1.docker.io/v2/ | grep -i "^docker-distribution-api-version"
docker-distribution-api-version: registry/2.0
  • /v2/ answers 401: the endpoint exists and wants a token. That's the live version.
  • /v1/_ping answers 404: the old v1 registry API was retired years ago. Old Docker clients that only spoke v1 can't pull images any more.
  • The docker-distribution-api-version: registry/2.0 header tells every client which protocol version it's talking to.

Real engineering

  • Design for additivity from day one: wrap lists in objects ({"items": [...]}) so you can add metadata later, use objects instead of bare strings for things that may grow, and document that enums may gain values.
  • Write tolerant clients and SDKs: ignore unknown fields, give unknown enum values a fallback, never depend on field order.
  • Catch breaking changes automatically. Diff each pull request's OpenAPI spec against the published one (tools like oasdiff do this) and fail the build on removed fields, changed types or new required parameters. Consumer contract tests (Pact) let client teams tell you what they rely on.
  • Version the whole API, not each endpoint, and keep the number of live versions small (usually two). Each extra version multiplies testing.
  • Track usage per version and per client. You can't sunset what you can't measure. Log the version and client identity on every request.
  • For mobile apps, plan for old versions forever-ish. Keep a minimum supported app version you can raise, and a way to show "please update" before an old version stops working.
  • Internal services aren't exempt. Another team's service is a client you don't deploy. The same rules apply, plus expand-and-contract for database changes: add the new column, write both, move readers, then drop the old one.

When it breaks

Try each case

Pick a failure

TypeError: cannot read property 'name' of undefined
breaks: A field was renamed inside the current version. Restore it; ship the new name alongside, and remove the old one only in a new version.

Think before you read on

Some teams avoid version numbers entirely and promise "we will never make a breaking change". Is that realistic, and what do they have to do instead?

Reveal

It's realistic for many APIs, and it's what GraphQL APIs and plenty of REST APIs do, but it has a price. Every change must be additive: instead of renaming name, you add full_name and keep name working, marked deprecated in the docs, possibly forever. Instead of changing a type, you add a new field. Over years the API collects old fields that can never be removed, unless you can measure that nobody reads them any more. So "no versions" really means "evolve only by adding, track field-level usage, and accept some clutter". Versioning means "occasionally break cleanly, behind a new number, and pay for running two versions for a while". Both are valid; doing neither (breaking in place) is not.

Check yourself

1. What makes a change backward-compatible?

Answer

Existing clients keep working without any change on their side. Typically: adding optional response fields, new endpoints or new optional request parameters. Removing, renaming, retyping or changing the meaning of anything is breaking.

2. What's a tolerant reader, and why does it matter?

Answer

A client that reads only the fields it needs and ignores unknown ones. Without it, even additive server changes (a new field) break clients, so the server could never evolve without a new version.

3. Why should requests with no version not get the latest version?

Answer

Because the latest changes with every release. A client that never chose a version would silently get breaking changes. A fixed default (or the account's pinned version) keeps behaviour stable.

4. How do you retire an old version politely?

Answer

Announce it with a date, add Deprecation and Sunset headers to its responses, measure who still calls it and contact them, raise minimum app versions if needed, and on sunset day return 410 Gone with a pointer to the new version.

Your challenge: header versioning and usage counts

Extend the server:

  • Accept the version from an API-Version header (1 or 2) as well as the path. If both are present and disagree, return 400.
  • Count requests per version in a map, and print the counts at the end.
  • Send: /v1/users/42, /users/42 with API-Version: 2, /users/42 with no version, and /v2/users/42 with API-Version: 1.

Before you run it, predict the four status codes and the final counts.

You've succeeded when the responses are 200 (v1), 200 (v2), 200 (v1, default) and 400 (conflict), and the counts print as v1=2 v2=1, with the rejected request not counted.

The mental model

Once anyone depends on your API, its responses are a contract you can't update on their side. Evolve by adding: new optional fields, endpoints and parameters, read by tolerant clients that ignore what they don't know. Removing, renaming, retyping or changing meaning is breaking, so it goes into a new version that runs beside the old one as a thin adapter over the same core. Give unversioned requests a fixed default, measure usage per version, deprecate loudly with Deprecation and Sunset headers, and retire old versions on a date with 410 Gone.

Station stamp

Finish the chapter

Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.

Go Pro to earn XP →