Part 03 · The Language of the Web
API Versioning and Compatibility
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
| Change | Example | Old clients |
|---|---|---|
| Add an optional field to a response | add email | fine, if they ignore unknown fields |
| Add a new endpoint | GET /users/42/badges | fine, they never call it |
| Add an optional request parameter | ?include=orders | fine, they don't send it |
| Remove or rename a response field | name → full_name | broken |
| Change a type or format | "price": "500" → "price": 500 | broken |
| Make an optional request field required | phone now required | broken: their requests start failing |
| Change meaning | amount in taka → in paisa | silently 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:
/v1sockets keep working while/v2is installed beside them.
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
- 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).
- 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.
- 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.
- Servers should be careful writers. Never remove, rename or retype a field inside a version. Keep defaults stable. Document which enums may grow.
- 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: 2or a date likeX-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.
- Path:
- 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. - 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.
- Deprecate, then sunset. Announce early, add
DeprecationandSunsetresponse headers (RFC 9745 and RFC 8594) to the old version, measure who still calls it, contact them, and only then turn it off, ideally returning410 Gonewith a link to the migration guide.
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
From launching v2 to switching off v1
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?
Can this ship without a new version?
new optional field
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))
}// A field is [name, value already written as JSON].
const obj = (fs) => "{" + fs.map(([k, v]) => `"${k}":${v}`).join(",") + "}";
// 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).
function user(version, change) {
if (version === "v2") { // v2 splits the name; that's why it's a new version
return [["id", "42"], ["first_name", '"Rahim"'], ["last_name", '"Uddin"']];
}
const fs = [["id", "42"], ["name", '"Rahim Uddin"']];
if (change === "email added") fs.push(["email", '"[email protected]"']);
if (change === "name renamed") fs[1][0] = "full_name";
return fs;
}
// The server picks the version from the path. No version means v1, and that default never changes.
function get(path) {
const parts = path.replace(/^\/|\/$/g, "").split("/");
let version = "v1";
if (/^v[0-9]/.test(parts[0])) version = parts[0]; // "v2", not "videos"
if (version === "v1") {
const note = path.startsWith("/v1") ? " Deprecation: true, Sunset: 2027-06-30" : " (no version: v1)";
return "200 " + obj(user("v1", "")) + note;
}
if (version === "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.
function oldApp(fs, strict) {
let name = "";
for (const [k, v] of fs) {
if (k === "id") continue;
if (k === "name") name = v.replace(/"/g, "");
else if (strict) return "broken: unknown field " + k;
}
if (name === "") return "broken: missing field name";
return "ok: " + name;
}
for (const p of ["/v1/users/42", "/v2/users/42", "/users/42", "/v9/users/42"]) {
console.log(`GET ${p.padEnd(13)} -> ${get(p)}`);
}
const cases = [
["v1 as it is", "v1", ""],
["v1 + email added", "v1", "email added"],
["v1 name renamed", "v1", "name renamed"],
["v2", "v2", ""],
];
console.log("old app (reads name), tolerant reader:");
for (const [label, version, change] of cases) {
console.log(` ${label.padEnd(17)} -> ${oldApp(user(version, change), false)}`);
}
console.log("old app (reads name), strict reader:");
console.log(` ${"v1 + email added".padEnd(17)} -> ${oldApp(user("v1", "email added"), true)}`);// A field is a name and its value already written as JSON.
type Field = (String, String);
fn obj(fs: &[Field]) -> String {
let parts: Vec<String> = fs.iter().map(|(k, v)| format!("\"{}\":{}", k, v)).collect();
format!("{{{}}}", parts.join(","))
}
fn f(k: &str, v: &str) -> Field {
(k.to_string(), v.to_string())
}
// 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).
fn user(version: &str, change: &str) -> Vec<Field> {
if version == "v2" {
// v2 splits the name; that's why it's a new version
return vec![f("id", "42"), f("first_name", "\"Rahim\""), f("last_name", "\"Uddin\"")];
}
let mut fs = vec![f("id", "42"), f("name", "\"Rahim Uddin\"")];
if change == "email added" {
fs.push(f("email", "\"[email protected]\""));
}
if change == "name renamed" {
fs[1].0 = "full_name".to_string();
}
fs
}
// The server picks the version from the path. No version means v1, and that default never changes.
fn get(path: &str) -> String {
let first = path.trim_matches('/').split('/').next().unwrap();
let b = first.as_bytes();
let version = if b.len() > 1 && b[0] == b'v' && b[1].is_ascii_digit() { first } else { "v1" }; // "v2", not "videos"
match version {
"v1" => {
let note = if path.starts_with("/v1") { " Deprecation: true, Sunset: 2027-06-30" } else { " (no version: v1)" };
format!("200 {}{}", obj(&user("v1", "")), note)
}
"v2" => format!("200 {}", obj(&user("v2", ""))),
_ => format!("400 {{\"error\":\"unknown version {}, supported: v1, v2\"}}", version),
}
}
// The old mobile app reads only "name". A tolerant reader ignores fields it doesn't know;
// a strict one rejects them.
fn old_app(fs: &[Field], strict: bool) -> String {
let mut name = String::new();
for (k, v) in fs {
match k.as_str() {
"id" => {}
"name" => name = v.trim_matches('"').to_string(),
_ => {
if strict {
return format!("broken: unknown field {}", k);
}
}
}
}
if name.is_empty() {
return "broken: missing field name".to_string();
}
format!("ok: {}", name)
}
fn main() {
for p in ["/v1/users/42", "/v2/users/42", "/users/42", "/v9/users/42"] {
println!("GET {:<13} -> {}", p, get(p));
}
let cases = [
("v1 as it is", "v1", ""),
("v1 + email added", "v1", "email added"),
("v1 name renamed", "v1", "name renamed"),
("v2", "v2", ""),
];
println!("old app (reads name), tolerant reader:");
for (label, version, change) in cases {
println!(" {:<17} -> {}", label, old_app(&user(version, change), false));
}
println!("old app (reads name), strict reader:");
println!(" {:<17} -> {}", "v1 + email added", old_app(&user("v1", "email added"), true));
}import re
def obj(fs):
"""A field is [name, value already written as JSON]."""
return "{" + ",".join(f'"{k}":{v}' for k, v in fs) + "}"
def user(version, change):
"""User 42 as a given version of the API represents it.
change simulates edits to v1: "email added" (additive) or "name renamed" (breaking)."""
if version == "v2": # v2 splits the name; that's why it's a new version
return [["id", "42"], ["first_name", '"Rahim"'], ["last_name", '"Uddin"']]
fs = [["id", "42"], ["name", '"Rahim Uddin"']]
if change == "email added":
fs.append(["email", '"[email protected]"'])
if change == "name renamed":
fs[1][0] = "full_name"
return fs
def get(path):
"""The server picks the version from the path. No version means v1, and that default never changes."""
parts = path.strip("/").split("/")
version = "v1"
if re.match(r"v[0-9]", parts[0]): # "v2", not "videos"
version = parts[0]
if version == "v1":
note = " Deprecation: true, Sunset: 2027-06-30" if path.startswith("/v1") else " (no version: v1)"
return "200 " + obj(user("v1", "")) + note
if version == "v2":
return "200 " + obj(user("v2", ""))
return f'400 {{"error":"unknown version {version}, supported: v1, v2"}}'
def old_app(fs, strict):
"""The old mobile app reads only "name". A tolerant reader ignores fields it doesn't know;
a strict one rejects them."""
name = ""
for k, v in fs:
if k == "id":
continue
if k == "name":
name = v.strip('"')
elif strict:
return "broken: unknown field " + k
if name == "":
return "broken: missing field name"
return "ok: " + name
for p in ["/v1/users/42", "/v2/users/42", "/users/42", "/v9/users/42"]:
print(f"GET {p:<13} -> {get(p)}")
cases = [
("v1 as it is", "v1", ""),
("v1 + email added", "v1", "email added"),
("v1 name renamed", "v1", "name renamed"),
("v2", "v2", ""),
]
print("old app (reads name), tolerant reader:")
for label, version, change in cases:
print(f" {label:<17} -> {old_app(user(version, change), False)}")
print("old app (reads name), strict reader:")
print(f" {'v1 + email added':<17} -> {old_app(user('v1', 'email added'), True)}")import java.util.*;
public class Main {
// A field is {name, value already written as JSON}.
static String obj(List<String[]> fs) {
List<String> parts = new ArrayList<>();
for (String[] f : fs) parts.add("\"" + f[0] + "\":" + f[1]);
return "{" + String.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).
static List<String[]> user(String version, String change) {
List<String[]> fs = new ArrayList<>();
if (version.equals("v2")) { // v2 splits the name; that's why it's a new version
fs.add(new String[]{"id", "42"});
fs.add(new String[]{"first_name", "\"Rahim\""});
fs.add(new String[]{"last_name", "\"Uddin\""});
return fs;
}
fs.add(new String[]{"id", "42"});
fs.add(new String[]{"name", "\"Rahim Uddin\""});
if (change.equals("email added")) fs.add(new String[]{"email", "\"[email protected]\""});
if (change.equals("name renamed")) fs.get(1)[0] = "full_name";
return fs;
}
// The server picks the version from the path. No version means v1, and that default never changes.
static String get(String path) {
String first = path.replaceAll("^/|/$", "").split("/")[0];
String version = first.matches("v[0-9].*") ? first : "v1"; // "v2", not "videos"
if (version.equals("v1")) {
String note = path.startsWith("/v1") ? " Deprecation: true, Sunset: 2027-06-30" : " (no version: v1)";
return "200 " + obj(user("v1", "")) + note;
}
if (version.equals("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.
static String oldApp(List<String[]> fs, boolean strict) {
String name = "";
for (String[] f : fs) {
if (f[0].equals("id")) continue;
if (f[0].equals("name")) name = f[1].replace("\"", "");
else if (strict) return "broken: unknown field " + f[0];
}
if (name.isEmpty()) return "broken: missing field name";
return "ok: " + name;
}
public static void main(String[] args) {
for (String p : List.of("/v1/users/42", "/v2/users/42", "/users/42", "/v9/users/42")) {
System.out.printf("GET %-13s -> %s%n", p, get(p));
}
String[][] cases = {
{"v1 as it is", "v1", ""},
{"v1 + email added", "v1", "email added"},
{"v1 name renamed", "v1", "name renamed"},
{"v2", "v2", ""},
};
System.out.println("old app (reads name), tolerant reader:");
for (String[] c : cases) System.out.printf(" %-17s -> %s%n", c[0], oldApp(user(c[1], c[2]), false));
System.out.println("old app (reads name), strict reader:");
System.out.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:
/v1and/v2live side by side, built from the same core user. v1 carriesDeprecationandSunset, 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
400that lists the supported ones, instead of silently falling back to something else. - Adding
emaildidn't break the tolerant old app: it readnameand 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/answers401: the endpoint exists and wants a token. That's the live version./v1/_pinganswers404: 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.0header 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
Pick a failure
TypeError: cannot read property 'name' of undefined
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-Versionheader (1or2) as well as the path. If both are present and disagree, return400. - Count requests per version in a map, and print the counts at the end.
- Send:
/v1/users/42,/users/42withAPI-Version: 2,/users/42with no version, and/v2/users/42withAPI-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 →