REST API design
Nouns, methods, status codes and errors that clients can trust, and changes that never break an app already in use.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
A food delivery app has an orders API. The mobile app shows a list of past orders with a price on each one. The API returns each order with a field called total.
A backend developer tidies up the code. He renames total to total_amount, because it is clearer. The web app is updated in the same release. All the tests pass.
The next morning, support gets angry messages. On the Android app, every order shows a price of ₹0. Some old iPhone versions crash on the orders screen.
The team checks the data. Many users had not updated the app in months. Those versions still read total, and now the field is gone. The team cannot force an update on every phone, so they put total back and send both fields.
This story is made up, but the mistake is common. A web page updates on every reload. A mobile app on a phone may be months old. Your API must serve all of them.
The idea in simple words
A REST API is built around resources: the nouns of your product. Orders, users and payments are resources. Each one has an address, like /orders/42. A group of them, like /orders, is a collection. 5
You act on resources with a few standard HTTP methods: GET, POST, PUT, PATCH and DELETE. You do not invent a new URL for every action. Google's guide says APIs should prefer standard methods over custom ones. 5
The server answers with a status code that tells the client what happened. When something goes wrong, it sends an error body in one fixed shape.
The key idea. An API is a promise to every client that uses it, including old ones you cannot update. Design it so you can add to it for years without breaking that promise.
How it works
Step through one order, from creation to an error. Use Next and Back, or the ← and → keys.
- The app creates an order. It sends POST to the orders collection with a new idempotency key, k-91. If it must retry, it sends the same key again.
- The server creates the order and answers 201 Created. The Location header gives the address of the new order, /orders/ord_42.
- The app reads the order with GET. GET is safe and idempotent: it asks for no change, so the app can repeat it if a request fails.
- The app lists orders, 20 at a time. The answer has a cursor, next_cursor. The app sends it back to get the next 20.
- The app sends a bad change: quantity -1. The server answers 422 with a problem details body. The type says what kind of error it is. The detail helps the client fix it.
Methods. RFC 9110 defines GET, HEAD, OPTIONS and TRACE as safe: the client does not ask for any change. PUT, DELETE and the safe methods are also idempotent: sending the same request twice has the same intended effect as sending it once. 1 POST is neither. PATCH is not idempotent by default either. 2
This matters for retries. RFC 9110 says a client should not retry a non-idempotent request automatically, unless it has some other way to know it is safe. 1 For POST, that way is an idempotency key. In its v1 API, Stripe accepts an Idempotency-Key header on every POST. If the same key comes with different parameters, it returns an error. 9
Status codes that matter. These cover most APIs. 1
- 200 OK: it worked, here is the result.
- 201 Created: a new resource exists. The
Locationheader points to it. - 204 No Content: it worked, and there is no body.
- 400 Bad Request: the request is broken, for example bad JSON.
- 401 Unauthorized: no valid login. 403 Forbidden: the server understood the request but refuses it, for example because the user lacks permission.
- 404 Not Found: no such resource. A server may also use it to hide a resource the user may not see.
- 409 Conflict: the request clashes with the current state, for example cancelling an order that has shipped.
- 422 Unprocessable Content: the syntax is fine, but the content makes no sense, like quantity -1.
- 500 Internal Server Error: a bug or surprise on the server.
- 503 Service Unavailable: overloaded or in maintenance, try later.
There is one more: 429 Too Many Requests means the client sent too many requests in a given time. It may carry a Retry-After header. 4 See Rate limiting.
One error format. RFC 9457 defines "problem details": a JSON body with the media type application/problem+json. It has five standard fields:
type: a URI that names the kind of problem.title: a short label for that kind of problem.status: the HTTP status code.detail: an explanation of this case, to help the client fix it.instance: a URI for this one occurrence.
You may add your own fields, and clients must ignore fields they do not know. 3 Pick one format and use it on every endpoint. Then clients write the error handling once.
Pagination and filtering. Never return a whole collection in one answer. Stripe uses cursor pagination: you send limit and starting_after, and the answer has has_more. 10 Google uses page_size, page_token and next_page_token, and its page tokens must be opaque. 6 Filters are query parameters, like GET /orders?status=shipped.
Add pagination from day one. Both Google and Microsoft say adding it later is a breaking change. 6 8
Versioning and compatibility. Adding something new, like a field or an endpoint, is usually safe. Removing a field breaks clients. Google treats renaming as "remove and add", so it breaks them too. Changing a field's type also breaks them. 7
When you must break something, release a new version and deprecate the old one slowly. Stripe puts /v1/ in the URL and sets a dated version per account. A client can choose another one with the Stripe-Version header. Since September 2024, its monthly versions have no breaking changes, and breaking ones come only twice a year. 11 Microsoft uses a required api-version query parameter with a date, like 2021-06-04. 8
Naming. Use plural nouns for collections, like /orders. Pick one style for field names and keep it everywhere. Microsoft uses camelCase for JSON fields. 8 Stripe uses snake_case, like has_more. 10 Both work. Mixing them does not.
Document it. The OpenAPI Specification is a standard way to describe an HTTP API in a file. People and tools can then understand the API without reading its code. Tools use the file to generate docs, client and server code, and tests. 13
When not REST. REST is a good default for public and mobile APIs, but not the only choice.
- gRPC: calls a method on another server as if it were local, with Protocol Buffers as the contract. It suits calls between your own services. 14
- GraphQL: the client asks for exactly the fields it needs, often in one request. It suits screens that need data from many resources. 15
- Webhooks: the server pushes events to your HTTPS endpoint when they happen. It retries failed deliveries, and the same event can arrive twice, so handle duplicates. 16 See webhooks and async APIs.
Trade-offs
| Pagination | How it works | Jump to page 7? | Stable while rows are added? | Use it when |
|---|---|---|---|---|
Offset (?offset=40&limit=20) | Skip 40 rows, return the next 20. | Yes Easy page numbers. | No Items can repeat or be skipped. Deep pages get slow, because the database still reads the skipped rows. 12 | Small lists that rarely change, like an admin table. |
Cursor (?cursor=c_7Hq&limit=20) | Return 20 rows after the item the cursor marks. | No You can only go next or back. There is no total page count. 12 | Yes The window does not move when new rows arrive. 12 | Feeds, messages, orders, any large or busy list. |
Simple rule: start with cursors and opaque tokens. You can always add filters later. You cannot easily switch a public API from offset to cursor without a new version.
At work: how a senior uses this
- Design the API from the client's screens first. Ask: "What does the app need to show, and in how many calls?"
- Treat every response field as a promise. Before you remove or rename one, ask: "Which app versions still read it?"
- Make new request fields optional. Google says new required fields must not be added to existing requests. 7
- For every POST that creates something or moves money, ask: "What happens if this runs twice?" Then add an idempotency key.
- Return 4xx for client mistakes and 5xx for server faults. Alerts on 5xx then mean real server problems.
- Use one error format on every endpoint. Put a stable error
typein it, so clients never parse the message text. - Write the OpenAPI file in the same pull request as the code. Review the file like code.
- Plan deprecation: tell clients early, measure who still calls the old version, and remove it only when traffic is near zero.
With AI
What to ask the agent
"Write an OpenAPI spec for an orders API: create, get, list with cursor pagination, and update. Use RFC 9457 problem details for every error. Use camelCase field names."
"Compare this OpenAPI file with the version on main. List every change that could break an existing client, like a removed, renamed or retyped field."
"Add an Idempotency-Key header to POST /orders. Store the key with the order in one transaction, and reject a reused key with a different body."
What to check yourself
- Field names, casing and plural collection names are the same on every endpoint.
- Every error uses the same problem details shape, with the right status code. No 200 with
"error": truein the body. - POST endpoints that create things take an idempotency key. GET never changes data.
- List endpoints are paginated, with a limit and a maximum page size.
- Nothing was removed, renamed or made required compared with the last version. An agent may "tidy up" names, just like the developer in the story.
- The status codes the code really returns match the ones in the OpenAPI file.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 16 sources and related lessons
- Fielding, Nottingham and Reschke, RFC 9110: HTTP Semantics (IETF, 2022), sections 9.2 and 15 (opens in a new tab)
Which methods are safe and idempotent, and what each status code means. - Dusseault and Snell, RFC 5789: PATCH Method for HTTP (IETF, 2010) (opens in a new tab)
The PATCH method, and why it is not idempotent by default. - Nottingham, Wilde and Dalal, RFC 9457: Problem Details for HTTP APIs (IETF, 2023) (opens in a new tab)
A standard JSON shape for error bodies, with type, title, status, detail and instance. - Nottingham and Fielding, RFC 6585: Additional HTTP Status Codes (IETF, 2012), section 4 (opens in a new tab)
The definition of 429 Too Many Requests. - Google, AIP-121: Resource-oriented design (opens in a new tab)
Resources as nouns, collections, and a small set of standard methods. - Google, AIP-158: Pagination (opens in a new tab)
Page tokens, page size, and why you add pagination from the first version. - Google, AIP-180: Backwards compatibility (opens in a new tab)
Which changes break old clients, such as removing or renaming a field. - Microsoft, Azure REST API Guidelines (GitHub, microsoft/api-guidelines) (opens in a new tab)
Naming, paging with nextLink, the api-version parameter and breaking changes. - Stripe API reference: Idempotent requests (opens in a new tab)
How a real API accepts an Idempotency-Key header on POST requests. - Stripe API reference: Pagination (opens in a new tab)
Cursor pagination with limit, starting_after and has_more. - Stripe API reference: Versioning (opens in a new tab)
Dated API versions, the Stripe-Version header, and monthly releases with no breaking changes. - Michael Hahn, “Evolving API Pagination at Slack”, Slack Engineering, 2017 (opens in a new tab)
Why Slack moved from offset to cursor pagination, and what cursors cannot do. - OpenAPI Initiative, OpenAPI Specification (opens in a new tab)
The standard file format that describes an HTTP API for people and tools. - gRPC documentation, “Introduction to gRPC” (opens in a new tab)
Calling a method on a remote server, with Protocol Buffers as the contract. - GraphQL Foundation, graphql.org (opens in a new tab)
A query language where the client asks for exactly the fields it needs. - Stripe documentation: Receive Stripe events in your webhook endpoint (opens in a new tab)
How a server pushes events to your HTTPS endpoint, with retries and duplicates.
Case studies: Stripe: Idempotency keys make API retries safe
Related: Idempotency, retries and timeouts · Rate limiting · API pagination and filtering · API versioning and deprecation · Schema evolution and encoding · RPC and gRPC (coming soon) · GraphQL and backend-for-frontend (coming soon) · Webhooks and async APIs
- Idempotency, retries and timeouts: how one retry can charge twice.
- Rate limiting: what to do before you send 429.
- Coming next on this line: API pagination and filtering and API versioning and lifecycle.