15 min read
API versioning best practices: change safely
In one sentence: Versioning an API means letting two forms of it live side by side, /v1/ and /v2/, so you can make a breaking change without breaking anyone. Almost everything is changed by adding; a new version comes to remove or change something, and the old one warns with Deprecation and Sunset before it goes away.
What you will learn
- Tell a breaking change from one that doesn't break anything.
- Serve two versions at once, with the old one as a layer that translates on top of the new one.
- Choose where the version goes, in the URL or in a header, and explain why almost everyone puts it in the URL.
- Announce that a version is being retired with the Deprecation, Sunset and Link headers.
Before you start, read: 03-pagination.md
The problem
Section titled “The problem”Luis wants to store prices in cents, 850 instead of 8.5, because with decimals, money calculations end up off by a cent (you’ll see it in lesson 6). Imagine that one Friday he changes the three prices in src/data.ts and deploys the server.
On Saturday, the shop’s mobile app shows the mug at €850, and nobody has touched the app. The server answers 200, TypeScript didn’t complain, and the JSON has the same shape as yesterday: {"id":2,"name":"Mug","price":850}.
What changed is the promise: the app and the delivery company have been reading price as euros for months. Once other programs use your APIAPI stands for Application Programming Interface.The way a program offers its services to other programs, that is, what you can ask it for and how it answers. The frontend talks to the backend through an API.Go to definition, any change can break them. In this lesson you learn to change it without them noticing.
The analogy
Section titled “The analogy”The analogy
Think of a shop that moves. It doesn’t close the old store the day the new one opens: for a few months both stay open, and in the old one’s window there’s a sign: “We’re moving. From April 13, at 5 New Street.” Whoever walks in buys as always and leaves knowing where to go.
To put a new product on the shelf, nobody moves. Moving is for what doesn’t fit in the usual store.
Where the analogy breaks down
- An API’s two stores share the warehouse: the old one reads the same data as the new one and only translates what changed.
- An API’s clients are programs and don’t read signs: the warning headers work if someone looks at them, and you also have to warn the people who maintain those programs.
How it really works
Section titled “How it really works”A change breaks if a client that worked stops working
Section titled “A change breaks if a client that worked stops working”A Breaking changeA change in an API that makes a client that used to work fail, without anyone touching it. Removing or renaming a field, changing its type or its unit, or requiring a new piece of data breaks clients; adding an optional field doesn’t.Go to definition is one that makes a ClientThe program that starts the conversation by asking another program, the server, for something. Your browser is a client.Go to definition that worked fail, without anyone touching it. The €850 mug is the worst kind: nothing throws an error, the data comes out wrong. The typical cases:
| Change | Does it break? | Why |
|---|---|---|
Adding a field to the response (stock) |
No | Whoever doesn’t know it ignores it |
Adding an optional parameter (?sort=price, from lesson 3) |
No | Whoever doesn’t send it gets the usual |
Adding a route (POST /orders/17/cancellation, from lesson 1) |
No | Nobody was calling it before |
Removing or renaming a field (price → priceCents) |
Yes | The client looks for price and it isn’t there |
| Changing a field’s type or unit (euros → cents) | Yes | The client reads a number that means something else |
| Making a piece of data that was optional required | Yes | The usual requests get a 422 |
| Validating more strictly (from 10 units per order to 5) | Yes | An order of 7 that was valid no longer is |
| Changing a status code or a URL | Yes | The client checks for the 200 or calls the old URL |
The underlying rule: adding almost never breaks; removing or changing almost always does. GitHub publishes a similar list in the documentation of its versions.
The gray area: a new value in a closed list
Section titled “The gray area: a new value in a closed list”In lesson 1, orders gained the cancelled status. GitHub counts a new value as an additive change, but if the delivery app only knows pending, paid and shipped, and crashes with any other, it did break that app. That’s why a good client is a tolerant reader: it ignores the fields it doesn’t know and treats an unknown status as “other.”
First: change by adding
Section titled “First: change by adding”Almost everything can be changed without breaking anything. The API could add priceCents next to price: old clients read price, new ones read priceCents, and nobody notices. What breaks is removing price.
You need a new version when the change can’t be made by adding:
- you want to remove something, like
price, so nobody uses it anymore; - what the client sends changes: creating a product asks for
priceCents, and?max=10becomes?maxCents=1000; - the meaning of something that already exists changes.
API versioningAPI stands for Application Programming Interface.Giving a number or a name to each shape an API has, so it can change without breaking whoever uses the previous one: /v1/ and /v2/ live side by side for a while and each client picks its own.Go to definition is that: giving each form of the API a number so the old one and the new one live side by side, and each client uses its own. The shop wants to remove price and change what clients send, so it will have two versions: v1, in euros, and v2, in cents.
Two versions at once, on the same data
Section titled “Two versions at once, on the same data”Copying all the code for the new version forces you to make every fix twice. In the project, the data and the routes are v2’s, and v1 is a thin layer that translates only what changed. This is how it answers the mobile app, which still speaks v1:
- Data (in cents) → v1.tspriceCents: 850
- v1.ts850 / 100 = 8.5
- v1.ts → Mobile app (v1)200, price: 8.5
and the warning headers
In src/app.ts, each version hangs from its prefix:
// Each version, under its prefix: /v1/products and /v2/products.app.route('/v1', v1);app.route('/v2', v2);
// The root says which versions there are and the status of each one.app.get('/', (c) => c.json({ name: "API for Ana and Luis's shop", versions: [ { version: 'v2', url: '/v2', status: 'current' }, { version: 'v1', url: '/v1', status: 'deprecated', sunset: SUNSET.toISOString() }, ], }),);app.route('/v1', v1)mountsv1’s routes under/v1: its/productsanswers at/v1/products. The same withv2.- The root,
/, says which versions there are and when the old one is retired. Routes without a version, like/products, give404.
In src/v1.ts, the first thing is the pieces that translate:
// A product the way version 1 gave it: the price, in euros.function productV1(product: Product) { return { id: product.id, name: product.name, price: product.priceCents / 100 };}
// Version 1's schemas, with the price in euros.const productSchemaV1 = z.object({ name: nameSchema, price: z .number({ error: 'Must be a number' }) .positive('Must be greater than 0') .max(10_000, 'At most €10,000'),});
const filterSchemaV1 = z.object({ max: z.coerce.number({ error: 'Must be a number' }).positive('Must be greater than 0').optional(), sort: filterSchema.shape.sort,});productV1receives a product in cents and returns another ObjectA value that groups several pieces of data, each with its own name, such as { name: "Mug", price: 8.5 }. Each piece is read with a period and its name, such as product.price.Go to definition with the old shape:price, in euros.- The two SchemaThe description of what some data must look like: which fields it has, whether each one is a number or text, and which values are accepted. A program compares the incoming data with it and says whether it matches or what’s wrong.Go to definition (Phase 3) say what
v1accepts when creating a product and in the Query stringThe part of a URL that comes after “?”: data in name=value pairs separated by “&”, such as q=mug&sort=price. It travels to the server attached to the path, and it’s used to search, filter or choose a page of results.Go to definition: euros.filterSchema.shape.sortreusesv2’s rule for?sort=, which doesn’t change.
The routes that read products are the ones from lesson 3, but before filtering and sorting they pass each product through productV1:
// Only the routes that changed: the ones that carry a price.v1.get('/products', validate('query', filterSchemaV1), (c) => { const { max, sort } = c.req.valid('query'); let list = products.map(productV1); if (max !== undefined) list = list.filter((product) => product.price <= max); if (sort === 'price') list = list.toSorted((a, b) => a.price - b.price); if (sort === '-price') list = list.toSorted((a, b) => b.price - a.price); return c.json(list);});
v1.get('/products/:id', validate('param', idSchema), (c) => { const product = findProduct(c.req.valid('param').id); if (!product) return httpProblem(c, 404, 'No such product'); return c.json(productV1(product));});And the one that creates a product, the only one that writes:
v1.post('/products', adminOnly, validate('json', productSchemaV1), (c) => { const { name, price } = c.req.valid('json'); // From euros to cents. Math.round, because 8.29 * 100 is 828.9999999999999. const product = createProduct(name, Math.round(price * 100)); return c.json(productV1(product), 201, { Location: `${c.req.path}/${product.id}` });});
// Everything else (the orders, deleting a product) hasn't changed: version 2's routes handle it.v1.route('/', v2);Math.round(price * 100)goes from euros to cents and rounds, because8.29 * 100gives828.9999999999999(lesson 6 tells you why).v1.route('/', v2)is the key: whateverv1doesn’t define (the orders, deleting a product) is handled byv2’s routes. Hono tries them in the order they were added:v1’s first.
In the URL or in a header?
Section titled “In the URL or in a header?”The version can travel in three places:
| Where | Example | Who uses it |
|---|---|---|
| In the URL | GET /v2/products |
The shop, and most public APIs |
| In a HeaderInformation a protocol puts in front of its data to do its job. In HTTP they are text lines of the form “Name: value”, such as Host or Content-Type; in TCP or IP they are numbers in fixed positions, such as ports or addresses.Go to definition | X-GitHub-Api-Version: 2026-03-10 |
GitHub; Stripe, with Stripe-Version |
| In the query string | GET /products?version=2 |
Few: it gets lost when links are copied |
Almost everyone chooses the URL because you can see it: in curl, in the browser, in the logs and in DevTools. The FrameworkReady-made code that solves what almost every program of one kind repeats, such as a server (reading each request, deciding which route handles it and responding), and that calls your functions when the time comes. You write only what’s specific to your application. Hono, Express and Fastify are frameworks for servers.Go to definition routes it with a prefix, and CacheA saved copy of an answer, so it doesn’t have to be fetched again. It saves time, at the cost of the copy possibly being stale until it expires.Go to definition store each version separately, because they’re different URLs.
With a header, each product has a single URL forever. In exchange, the version can’t be seen, and the response has to carry Vary with that header’s name, so a cache doesn’t give one client another client’s version (lesson 4 of Phase 2).
GitHub uses the header, with dates as names. If you don’t send it, it chooses for you:
The version GitHub chooses if you say nothing
curl -sI https://api.github.com/repos/nodejs/node | grep -i versionWhat you will see:
x-github-api-version-selected: 2022-11-28-sI asks only for the headers, and grep -i version keeps the lines that say version. Without the header, GitHub uses 2022-11-28; the new one is 2026-03-10, and the previous one lasts at least 24 more months. Output from October 13, 2026: if GitHub changes the default version, you’ll see another date.
Warn before switching off: Deprecation, Sunset and Link
Section titled “Warn before switching off: Deprecation, Sunset and Link”An old version isn’t switched off from one day to the next: first it’s declared DeprecatedSaid of a part of an API that still works but is no longer recommended, because it’s going to be removed. In HTTP, the Deprecation header warns that something is deprecated, and the Sunset header says when it will stop working.Go to definition, and it keeps working for a while. v1 announces it in every response:
// Since when it's deprecated (RFC 9745: the seconds since 1970, with an @ in front) and when it// will stop working (RFC 8594: an HTTP date, like the one in Expires).const DEPRECATED_SINCE = new Date('2026-10-13T00:00:00Z');export const SUNSET = new Date('2027-04-13T00:00:00Z');
// Every v1 response says so in its headers, and says where the same thing is in version 2.v1.use(async (c, next) => { await next(); c.header('Deprecation', `@${DEPRECATED_SINCE.getTime() / 1000}`); c.header('Sunset', SUNSET.toUTCString()); const successor = c.req.path.replace(/^\/v1/, '/v2'); // append: the response may already carry a Link (the next page) and it mustn't be deleted. c.header('Link', `<${successor}>; rel="successor-version"`, { append: true });});v1.use(…)is a MiddlewareA function a server runs with the requests of the routes it’s registered on (all of them, or only some), before the code that answers them. It can answer the request itself or pass it on to the next one, and it sees the response on its way back. It’s used for what affects many requests, like writing them to the log, granting CORS permission or asking for a credential.Go to definition (lesson 6 of Phase 3) for all ofv1’s routes, including the onesv2handles. It callsnext()and, when the response comes back, adds three headers to it.Deprecationsays since when it’s deprecated. It’s defined by RFC 9745, from 2025: an@and the seconds since January 1, 1970, in universal time.getTime()gives milliseconds: that’s why it’s divided by 1000.Sunsetsays when it will stop working. It’s defined by RFC 8594, with the date format ofDateorExpires, the onetoUTCString()writes. RFC 9745 forbids it from being earlier than theDeprecationdate.Link, withrel="successor-version", says where the same thing is in the new version: lesson 3’sLinkheader, with another relation.replace(/^\/v1/, '/v2')changes the/v1at the start of the path to/v2(what goes between slashes is a pattern, and^means “at the start”).{ append: true }adds theLinkwithout deleting any that was already there, like the next page’s.
Declaring something deprecated changes nothing else: according to RFC 9745, the response works the same as without the header. It’s a warning, not an error.
After the date: see who’s left and switch off
Section titled “After the date: see who’s left and switch off”Before April 13, look at who’s still calling v1: the log from lesson 8 of Phase 3 records each path, and grep '"path":"/v1/' shop.log tells you. Write to whoever is left.
When the date arrives, RFC 8594 doesn’t set what happens: a 4xx error, a 3xx redirect or no response at all. The clearest is its example, 410 Gone: “this existed and is no longer here,” different from the 404 of what never existed (lesson 3 of Phase 2).
Try it
Section titled “Try it”The goal: move prices to cents without the mobile app, which still reads euros, noticing anything, and check that v1 warns that it’s being retired. You start from your project from lesson 3 in ~/backend-course/phase-3/shop-api. Also download this lesson’s folder, which brings the tests and helps you compare if you get stuck: from ~/backend-course/phase-3, curl -O https://backenddesdecero.com/practicas/shop-api/13-versioning.tar.gz and tar -xzf 13-versioning.tar.gz.
The shortcut: cents in the same field
Section titled “The shortcut: cents in the same field”First, the change from “The problem,” to see what catches it. In src/data.ts, change the three prices: 20 to 2000, 8.5 to 850 and 35 to 3500. Run the tests:
1. The tests, with the shortcut
npm test | tail -n 35What you will see:
ℹ tests 32ℹ suites 0ℹ pass 31ℹ fail 1ℹ cancelled 0ℹ skipped 0ℹ todo 0ℹ duration_ms 1092.922465
✖ failing tests:
test at test/pagination.test.ts:84:1✖ the products, sorted by price both ways and filtered (1.370873ms)AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:+ actual - expected
[+ 850,+ 2000,+ 3500- 8.5,- 20,- 35 ]
at TestContext.<anonymous> (file:///Users/ana/backend-course/phase-3/shop-api/test/pagination.test.ts:87:10) at async Test.run (node:internal/test_runner/test:1409:7) at async Test.processPendingSubtests (node:internal/test_runner/test:974:7) { generatedMessage: true, code: 'ERR_ASSERTION', actual: [ 850, 2000, 3500 ], expected: [ 8.5, 20, 35 ], operator: 'deepStrictEqual', diff: 'simple'}tail -n 35 keeps the last 35 lines. The test that sorts by price fails: it expected 8.5, 20, 35 (the lines with -) and gets 850, 2000, 3500 (the ones with +). It reads price as euros, just like the app. npm run check doesn’t complain: 850 is still a number.
This lesson’s outputs are from Node 26.11.1 and curl 8.14.1, on Linux; your times and dates will be different. If you see tests 0, you’re missing the test/ folder from lesson 3’s download.
Undo the change: put back 20, 8.5 and 35.
Version 2: cents with their own name
Section titled “Version 2: cents with their own name”- Create
src/v2.ts. Move into it, fromsrc/app.ts, the/productsand/ordersroutes, thestatusDoesNotAllowandnotAllowedfunctions and theimports they use, and changeapp.tov2.. - In
src/data.ts, changepricetopriceCentsinProduct, in the three products (2000,850and3500) and increateProduct:
// From version 2, the price is in whole cents: 850, not 8.5. With decimals, money calculations end// up off by a cent (lesson 6).export interface Product { id: number; name: string; priceCents: number;}- In
src/schemas.ts, the new product asks for whole cents, with.int(…), and the filter is now calledmaxCents. The name rule moves out to a constant withexport,nameSchema, becausev1uses it too (in the download, right before the product).
// A new product in version 2: the price, in whole cents.export const productSchema = z.object({ name: nameSchema, priceCents: z .number({ error: 'Must be a number' }) .int('Must be a whole number of cents') .positive('Must be greater than 0') .max(1_000_000, 'At most 1,000,000 cents (€10,000)'),});// What comes in the path and in the query string is always text: coerce turns it into a number.export const idSchema = z.object({ id: z.coerce.number({ error: 'Must be a number' }).int('Must be a whole number'),});
export const filterSchema = z.object({ maxCents: z.coerce .number({ error: 'Must be a number' }) .int('Must be a whole number of cents') .positive('Must be greater than 0') .optional(), // price, from lowest to highest; -price, from highest to lowest. sort: z.enum(['price', '-price'], { error: 'Must be price or -price' }).optional(),});- In
src/v2.ts, the product routes use the new names. This is how the file starts, after theimports, and this is how the create route ends up:
export const v2 = new Hono();
v2.get('/products', validate('query', filterSchema), (c) => { const { maxCents, sort } = c.req.valid('query'); let list = products; if (maxCents !== undefined) { list = list.filter((product) => product.priceCents <= maxCents); } // toSorted sorts a copy: the original list's order doesn't change. if (sort === 'price') list = list.toSorted((a, b) => a.priceCents - b.priceCents); if (sort === '-price') list = list.toSorted((a, b) => b.priceCents - a.priceCents); return c.json(list);});// Create: POST to the collection. Location is built from the request's path (/v2/products), so it// works the same in any version.v2.post('/products', adminOnly, validate('json', productSchema), (c) => { const { name, priceCents } = c.req.valid('json'); const product = createProduct(name, priceCents); return c.json(product, 201, { Location: `${c.req.path}/${product.id}` });});c.req.path is the request’s path, with its prefix: /v2/products or /v1/products. Change the Location of POST /orders the same way: c.req.path, a slash and order.id.
npm run check guides you: every price left over comes out like this (your file and your line will be different):
src/v2.ts(32,45): error TS2339: Property 'price' does not exist on type 'Product'.Version 1, on top of version 2
Section titled “Version 1, on top of version 2”Create src/v1.ts with these imports and, below them, the four pieces from “How it really works,” in order: warnings, translate, read and create.
import { Hono } from 'hono';import { z } from 'zod';import { createProduct, findProduct, products, type Product } from './data.ts';import { adminOnly } from './middleware/admin-only.ts';import { validate } from './middleware/validate.ts';import { httpProblem } from './problems.ts';import { filterSchema, idSchema, nameSchema } from './schemas.ts';import { v2 } from './v2.ts';
export const v1 = new Hono();In src/app.ts the imports change, and the routes make room for the versions part; the rest (requestId, the log, CORS and the errors) stays the same:
import { Hono } from 'hono';import { cors } from 'hono/cors';import { HTTPException } from 'hono/http-exception';import { requestId } from 'hono/request-id';import { log } from './log.ts';import { requestLog } from './middleware/request-log.ts';import { httpProblem, problem } from './problems.ts';import { SUNSET, v1 } from './v1.ts';import { v2 } from './v2.ts';Lesson 3’s tests call /products without a version, which is now a 404. Copy the ones from the download and run them:
2. The tests of both versions
cp ../13-versioning/test/*.test.ts test/npm test | tail -n 17What you will see:
✔ the root says which versions there are and when version 1 is retired (7.706782ms)✔ v2: the price, in whole cents (1.342706ms)✔ v1 stays as it was: the price, in euros (1.747956ms)✔ v1 warns that it is deprecated, when it is retired and where version 2 is (0.940916ms)✔ v2 does not carry those warnings (0.452333ms)✔ a product created with v1, in euros, reads in v2 in cents (2.541789ms)✔ in v2, the price in euros is no longer valid: it is a breaking change (1.397707ms)✔ v1's orders are v2's, with the warnings and without losing the next page's Link (1.125582ms)✔ without a version, the routes no longer exist: 404 (0.743582ms)ℹ tests 41ℹ suites 0ℹ pass 41ℹ fail 0ℹ cancelled 0ℹ skipped 0ℹ todo 0ℹ duration_ms 540.725558The nine from test/versioning.test.ts, and fail 0 out of 41. If any fails, it comes out with ✖, what it expected and what it got: compare your code with the download’s.
Call both versions
Section titled “Call both versions”Start the server with npm run dev and open another terminal for curl.
3. The root: which versions there are
curl -s localhost:3000/ | jqWhat you will see:
{"name": "API for Ana and Luis's shop","versions": [ { "version": "v2", "url": "/v2", "status": "current" }, { "version": "v1", "url": "/v1", "status": "deprecated", "sunset": "2027-04-13T00:00:00.000Z" }]}jq (lesson 8 of Phase 3) lays the JSON out in lines. v1 is deprecated and has a retirement date.
4. The mug, in v1
curl -i localhost:3000/v1/products/2What you will see:
HTTP/1.1 200 OKcontent-type: application/jsondeprecation: @1791849600link: </v2/products/2>; rel="successor-version"sunset: Tue, 13 Apr 2027 00:00:00 GMTvary: Originx-request-id: 455e55de-f5af-41ef-ab4a-7e41d5a840decontent-length: 33Date: Tue, 13 Oct 2026 15:39:31 GMTConnection: keep-aliveKeep-Alive: timeout=5
{"id":2,"name":"Mug","price":8.5}A 200 and the mug at €8.50: the app notices nothing. But the three warnings come along: deprecated since @1791849600, switched off on April 13, 2027, and the same mug at /v2/products/2. date -u -r 1791849600 on the Mac (date -u -d @1791849600 on Linux and WSL) translates the number: Tue Oct 13 00:00:00 UTC 2026. Your x-request-id and your date will be different.
5. The same mug, in v2 and without a version
curl -w '\n' localhost:3000/v2/products/2curl -w '\n' localhost:3000/products/2What you will see:
{"id":2,"name":"Mug","priceCents":850}{"type":"about:blank","title":"Not Found","status":404,"detail":"No such route"}In v2, priceCents: 850, without warnings. Without a version, a 404 in lesson 2’s format.
Now create a product through v1, in euros, and read it through v2. First, save your token in a terminal variable: TOKEN= and, right after it, the value of ADMIN_TOKEN from your .env.
6. A cap created in euros, read in cents
curl -i -w '\n' -H "Authorization: Bearer $TOKEN" --json '{"name":"Cap","price":8.29}' localhost:3000/v1/productscurl -w '\n' localhost:3000/v2/products/4What you will see:
HTTP/1.1 201 Createdcontent-type: application/jsondeprecation: @1791849600link: </v2/products>; rel="successor-version"location: /v1/products/4sunset: Tue, 13 Apr 2027 00:00:00 GMTvary: Originx-request-id: af720d9c-e37d-48c8-88bb-383072eddb33content-length: 34Date: Tue, 13 Oct 2026 15:39:31 GMTConnection: keep-aliveKeep-Alive: timeout=5
{"id":4,"name":"Cap","price":8.29}{"id":4,"name":"Cap","priceCents":829}A single product, from both versions: €8.29 in v1 and 829 cents in v2. The double quotes let the terminal replace $TOKEN with its value; if you get a 401, the variable is empty or the token doesn’t match.
7. The old filter, in both versions
curl -w '\n' 'localhost:3000/v1/products?max=10'curl -w '\n' 'localhost:3000/v2/products?maxCents=1000'curl -w '\n' 'localhost:3000/v2/products?max=10'What you will see:
[{"id":2,"name":"Mug","price":8.5},{"id":4,"name":"Cap","price":8.29}][{"id":2,"name":"Mug","priceCents":850},{"id":4,"name":"Cap","priceCents":829}][{"id":1,"name":"T-shirt","priceCents":2000},{"id":2,"name":"Mug","priceCents":850},{"id":3,"name":"Hoodie","priceCents":3500},{"id":4,"name":"Cap","priceCents":829}]The first two give the same thing, each in its own language. The third, ?max=10 in v2, returns all four products, without an error: Zod drops whatever isn’t in the schema, and v2’s doesn’t know max. Moving to another version isn’t changing /v1 to /v2 in the URL: you have to change every name.
8. A list of orders from v1
curl -sI 'localhost:3000/v1/orders?limit=2' | grep -iE '^(http|deprecation|sunset|link)'What you will see:
HTTP/1.1 200 OKdeprecation: @1791849600link: <http://localhost:3000/v1/orders?limit=2&cursor=MjQ>; rel="next", </v2/orders>; rel="successor-version"sunset: Tue, 13 Apr 2027 00:00:00 GMTThe orders are handled by v2, through v1.route('/', v2), with v1’s warnings. Thanks to { append: true }, the Link carries two links separated by a comma: the next page, in v1, and the successor version.
You have already seen it
Section titled “You have already seen it”- “Update the app to keep using it.” Often, the server is about to switch off the API version your old app uses.
- In URLs. In DevTools’ Network tab (how to open them) you’ll see requests to
/api/v1/…or/v3/…. - In npm packages. The
4inhono@4.13.18changes when something breaks (lesson 1 of Phase 3). APIs usually use only that number, or a date, almost neverv2.3.1: the client only cares about when something breaks.
Common mistakes
Section titled “Common mistakes”- Changing the meaning without changing the name. Cents in the same
pricedon’t throw any error: they give prices a hundred times higher. - Releasing a version for every change. Whatever can be added is added in the current version.
- Copying all the code for the new version. The copies drift apart with every fix: let the old one translate on top of the new one.
- Setting
Sunsetand not checking who’s left. Before switching off, look at the log and write to whoever is still on the old one. - Sending the old parameters to the new version.
?max=10inv2doesn’t give an error: it’s silently ignored.
Summary
Section titled “Summary”- A change breaks if a client that worked stops working: removing or renaming a field, changing its type or unit, requiring something new.
- First, change by adding. A new version is for removing something, or for changing what the client sends or what something means.
- Both versions live side by side on the same data: the old one translates only what changed.
- Almost every API puts the version in the URL (
/v2/): you can see it, and caches don’t mix versions. - The old one warns with
Deprecation(since when it’s deprecated),Sunset(when it’s switched off) andLinkwithrel="successor-version"(where the new one is).
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- RFC 9745: The Deprecation HTTP Response Header Field: the
Deprecationheader andrel="deprecation", to link to a page that explains the retirement. - RFC 8594: The Sunset HTTP Header Field: the
Sunsetheader and what can happen after the date. - API versions (GitHub): which changes break and how long each version lasts.
- Versioning (Stripe): versions with a date in a header, with the
/v1/in the URL.