Designing APIs Like a Senior Engineer: Contracts, Versioning, and Backward Compatibility
From Mid-Level to Senior · Part 6 of 18
- #api-design
- #rest
- #backward-compatibility
- #senior-engineer
- #engineering-practices
When you write a private method, you can rename it whenever you like. The compiler finds every caller, you fix them in the same commit, and nobody outside your team ever knows.
An API doesn't give you that. The moment a mobile app, a partner, or even another team in your own company starts calling your endpoint, the shape of that endpoint stops being an implementation detail. It's a contract. Some of the callers you know about. Some you don't. A few of them shipped an app build six months ago that people still have on their phones and will never update.
In Part 5 we looked at the quality of the code itself. This part goes one level out, to the code other people depend on. If you went through the beginner REST API post in Track 1, you already know how to build an endpoint. The question now is how to design one you can still live with two years from now.
The contract is everything a client can observe
People tend to think the contract is the OpenAPI file. It isn't, or at least not only that. The real contract is anything a client can see and might reasonably rely on:
- field names, types, and whether a field can be
nullor missing - status codes, including which errors you return and when
- the order of items in a list, if you've always returned them sorted
- default values, page sizes, timeouts, rate limits
- the format of IDs and dates
That last group is where people get surprised. You never documented that
/orders comes back newest first. But it always has, and somebody's code
takes items[0] as "the latest order". Change the sort and you've broken
them, spec or no spec. (There's a name for this, Hyrum's Law: with enough
users, every observable behaviour will be depended on by somebody.)
So before you ship an endpoint, ask what you're promising, including the
things you didn't mean to promise. Then either commit to them on purpose or
document that they aren't guaranteed (order is undefined unless you pass
sort, for example).
Model resources, not database tables
The easiest API to build is one that mirrors your entities. You have an
Order table, so you have /orders, and the JSON has the same columns.
It's quick, and it ties your public contract to your schema forever. The
next time you split a table or rename a column, you're now doing an API
migration too.
A few guidelines that hold up well:
- Design from the client's use case. What does the screen or the partner integration actually need? Start there, then map it to your data. Not the other way round.
- Use nouns for resources, HTTP methods for verbs.
POST /orders,GET /orders/{id},DELETE /orders/{id}. When an action doesn't fit CRUD, like cancelling, a sub-resource such asPOST /orders/{id}/cancelis honest and easy to read. Don't twist it into aPATCHthat setsstatus: "CANCELLED"if cancelling also refunds payment and sends emails. - Use opaque, stable IDs. Exposing auto-increment integers leaks how
many orders you have and invites people to guess
id + 1. A UUID or a prefixed string (ord_8f3k2...) costs nothing and keeps your options open. - Be boringly consistent. Pick
camelCaseorsnake_case, pick one date format (ISO 8601 with a timezone, please), pick how you name collections, and never deviate. Clients learn your conventions once and guess the rest.
Pagination and filtering: decide before you have data
Every list endpoint should be paginated from day one, even if the table has twelve rows. Adding pagination later is a breaking change: clients that expected the whole list will silently get the first page and think that's all there is.
There are two common styles:
Offset pagination (?page=3&size=50) is simple and lets users jump to
page 40. But it gets slow on large tables, because the database still has to
walk past every skipped row. And it's unstable: if a new item is inserted
while someone is paging, they'll see one item twice or miss one.
Cursor pagination (?limit=50&after=eyJpZCI6...) returns an opaque
token pointing at the last item you saw. It stays fast at any depth and
doesn't skip or repeat items when data changes. The cost is that you can't
jump to an arbitrary page.
My default for anything that can grow is cursor-based, with the cursor kept opaque (base64 of whatever you need internally) so you can change what's inside it later. A response looks something like this:
{
"items": [ { "id": "ord_8f3k2", "status": "PAID" } ],
"nextCursor": "eyJjcmVhdGVkQXQiOiIyMDI2LTEwLTA1In0",
"hasMore": true
}
Notice the list is wrapped in an object rather than returned as a bare JSON
array. That one choice is what lets you add nextCursor, hasMore, or a
totalCount later without breaking anyone. A top-level array has nowhere
to put new information.
For filtering, keep it explicit and limited. ?status=PAID&createdAfter=...
for the filters you actually support beats a generic query language you'll
have to keep working forever. Whatever you allow in a filter, you're
committing to index and keep fast.
One error shape, everywhere
Clients spend a surprising amount of code handling errors, so give them one
shape to handle. Spring's ProblemDetail (covered in the
validation post) implements
the problem+json standard (RFC 9457, which replaced RFC 7807), and it's a
perfectly good default.
The thing I'd add on top is a stable, machine-readable error code:
{
"type": "https://api.example.com/errors/insufficient-stock",
"title": "Insufficient stock",
"status": 409,
"code": "INSUFFICIENT_STOCK",
"detail": "Only 2 units of SKU-1042 are available.",
"instance": "/orders/ord_8f3k2"
}
detail is for humans and you should feel free to reword it. code is for
programs, and it's part of the contract. If clients have to parse your
English message to figure out what went wrong, you can never fix a typo in
that message again.
A few more rules worth following:
- 4xx means the client can fix it. 5xx means it's on you. Don't return 500 for a validation error or 400 for a database timeout.
- Never leak stack traces, SQL, or internal class names.
- Document which errors each endpoint can return. "It may return 409
INSUFFICIENT_STOCK" is part of the API, the same as the success response.
Idempotency: assume every request will be sent twice
Networks fail in the worst possible place: after your server did the work, but before the client got the response. The client sees a timeout, retries, and now the customer has been charged twice.
GET, PUT, and DELETE are supposed to be idempotent by definition.
Doing them twice leaves things in the same state as doing them once. POST
isn't, and POST is usually where the money moves.
The standard fix is an idempotency key. The client generates a unique key per logical operation and sends it in a header. The server remembers it:
Some details that matter in practice:
- Store the key and the response together, atomically with the work. If you save the key in one transaction and create the payment in another, you've only moved the race condition.
- Reject a reused key with a different body. That's a client bug, and silently returning the old response would hide it. 422 (or 409) with a clear error code is fine.
- Give keys an expiry, like 24 hours, and document it.
- Handle the in-flight case. If the second request arrives while the first is still running, return a 409 asking the client to retry shortly rather than processing both.
You don't need this on every endpoint. You do need it on anything that creates something, sends something, or charges something.
Additive change vs. breaking change
This is the core skill. Most of the time, you can evolve an API without a new version at all, as long as every change is additive: it adds something clients can ignore, and it doesn't change what existing clients already rely on.
Two of those deserve a closer look.
New enum values. Adding "REFUNDED" to an order status looks additive.
But if a client has a switch over every status and throws on unknown ones,
it breaks the moment the first refunded order shows up. Say in your docs
from day one that enums can grow and clients must handle unknown values.
Then, when you do add one, announce it anyway.
Unknown fields. The whole "adding a field is safe" idea assumes clients ignore fields they don't recognise. Jackson does this by default in Spring Boot, but plenty of strict clients don't. It's worth stating in your API guidelines: "Clients must ignore unknown fields." That one sentence buys you years of room to evolve.
And when you're the one consuming an API, be the client you'd want: ignore unknown fields, have a default branch for unknown enum values, and don't depend on behaviour that isn't documented.
Versioning: the last resort, not the first
Sometimes a breaking change is genuinely worth it. Then you need a version. The common options are:
- In the path:
/v2/orders. Very visible, easy to route, easy to see in logs. This is what most public APIs do, and it's my default. - In a header:
Accept: application/vnd.example.v2+jsonor anApi-Versionheader. Cleaner URLs, but easy for clients to forget. - Date-based versions pinned per client, the way Stripe does it. Very nice for consumers, and a real engineering investment for whoever runs it.
Whatever you pick, version the whole API, not individual endpoints.
/v2/orders next to /v1/customers next to /v3/payments becomes a puzzle
nobody can follow.
More important than the mechanism: every version you ship is a version you have to run. Two versions means two sets of tests, two code paths through every bug fix, two things to keep secure. That's why additive change should be your first move, and a new version only what you do when there's no additive way out.
Deprecation is a process, not an announcement
Removing something from an API takes weeks or months, not one commit. A deprecation that works looks roughly like this:
The step people skip is measuring. If you can't tell who still calls the old endpoint, you're guessing, and the person who finds out you guessed wrong is a customer. Two things make measuring possible:
- Know your clients. Require an API key or client ID on every request, even internal ones, so you can see who is calling, not just how much.
- Use the standard headers. The
DeprecationandSunsetHTTP headers let well-behaved clients warn their own developers automatically.
Set a sunset date and stick to it, but leave room for the one important consumer who needs an extra month. Being firm and humane at the same time is most of the job.
Design it on paper first
All of this is cheaper to get right before the code exists. For any
endpoint other teams will call, write the contract first (an OpenAPI
snippet, or just example requests and responses in a PR) and get it reviewed
by someone who will actually consume it. Ten minutes of "wait, how would I
page through this?" saves you a /v2 a year later.
What to try this week
- Pick one endpoint you own and list everything a client can observe about it, including the undocumented parts. Anything surprising on that list?
- Check your list endpoints. Are they all paginated, and do they return an object rather than a bare array?
- Look at your error responses. Is there a stable
codefield, or are clients parsing messages? - Find one
POSTthat creates or charges something, and ask what happens if it's sent twice.
The short version
- The contract is everything a client can observe, not just what's in the spec.
- Model resources from the client's needs, not your tables. Use opaque IDs and boring, consistent conventions.
- Paginate from day one, wrap lists in an object, and prefer cursors for anything that grows.
- One error shape everywhere, with a stable machine-readable code.
- Make anything that creates, sends, or charges idempotent.
- Evolve additively by default. Version only when there's no other way, and version the whole API.
- Deprecate in stages: replace, announce, measure, chase, remove.
An API is only as stable as the data model underneath it. In Part 7 we'll go one layer down: database design fundamentals, including normalization, indexing, and where those rules are meant to bend.
This is Part 6 of 18 in the series. The Senior Engineer Roadmap maps the whole series, with a short self-assessment and four reading orders.