Designing REST endpoints
Every endpoint you add is a promise to every client that calls it. Here is how to make those promises consistent and keep them: resources and methods, pages that hold still while data changes, and versions that let you change your mind.
01 Name things, not actions
An API grows one endpoint at a time, and each one gets named after what it does that day. A year later the client has to learn forty verbs: getUser, fetchUserPosts, removePost, updateUserEmail. REST asks for a different habit: the URL names a thing (a resource), and the HTTP method says what to do with it.
GET /getUser?id=7POST /createUserPOST /updateUserEmailGET /deleteUser?id=7GET /getPostsForUser?id=7
GET /users/7POST /usersPATCH /users/7DELETE /users/7GET /users/7/posts
Two kinds of URL do almost all the work: a collection (/users, plural noun) and an item in it (/users/7, the collection plus an id). Five methods on those two shapes cover create, read, update and delete for every resource you add, so a client that knows one resource can guess the next.
02 What each method promises
The method is not decoration. Browsers, caches, proxies and retry libraries read it and act on it, so each one comes with promises your server has to keep.
| Method | On /users | On /users/7 | Safe | Idempotent |
|---|---|---|---|---|
| GET | List users | Read user 7 | Yes | Yes |
| POST | Create a user | (rarely used) | No | No |
| PUT | (rarely used) | Replace user 7 with the body | No | Yes |
| PATCH | (rarely used) | Change some fields of user 7 | No | Not by default |
| DELETE | (rarely used) | Remove user 7 | No | Yes |
- Safe means the request changes nothing on the server. Link prefetchers and crawlers follow
GETlinks on their own, which is whyGET /deleteUser?id=7above is a real bug and not just ugly. - Idempotent means sending it twice has the same effect as sending it once.
DELETE /users/7twice still leaves user 7 gone (the second call may answer404, but the state is the same). Clients and proxies may retry idempotent requests after a timeout. POST /userstwice makes two users. If a client must retry a create, accept anIdempotency-Keyheader and return the first result for a repeated key.
Answer with status codes that match: 201 Created with a Location: /users/8 header for a create, 200 with the resource or 204 No Content for an update or delete, 404 for an id that does not exist, 409 Conflict when the email is taken, 422 (or 400) when the body fails validation.
03 Nesting, filters and awkward actions
Nest a resource under its parent when it only makes sense there: GET /users/7/posts lists one user’s posts. Stop at one level. Once a post has its own id, give it its own home, GET /posts/42, rather than /users/7/posts/42/comments/3; the deep path forces the client to know every parent just to reach a comment.
Filtering, sorting and choosing fields go in the query string, because they narrow the same collection rather than name a new one:
Some operations are not create, read, update or delete. Cancelling an order touches stock, refunds and email, and PATCH /orders/42 {"status":"cancelled"} hides all that behind a field change. Two honest options: a sub-resource for the action, POST /orders/42/cancel, or a resource for the thing the action creates, POST /refunds with the order id in the body. Both keep the verb POST for something that is neither safe nor idempotent.
04 Pagination: offset or cursor
A list endpoint must never return the whole table. It returns a page, and the question is how the client asks for the next one. The obvious way is offset: ?limit=3&offset=3 means skip three rows and return three. It breaks as soon as rows are added while someone is reading.
- rows this page returns
- just added
- shown twice
The table holds posts p9 down to p1, newest first. The client wants pages of 3 and has shown nothing yet.
A cursor fixes this by naming a position in the data instead of a row number. The cursor is the sort key of the last item returned, so the next query asks for rows past it.
- rows this page returns
- just added
Same table, same page size. This time the API pages by a cursor: the id of the last post the client saw.
Run against the 10 posts above, the offset query returns 7, 6, 5 and the cursor query 6, 5, 4 (checked in SQLite; Postgres behaves the same). The response carries the cursor so the client never builds it:
Keep the cursor opaque to clients (many APIs base64-encode it) so you can change what is inside later. When you sort by something that is not unique, such as created_at, put a tie-breaker in the cursor too: WHERE (created_at, id) < ($1, $2) ORDER BY created_at DESC, id DESC. Otherwise two posts with the same timestamp can fall between pages.
05 Changing the API without breaking clients
Once a mobile app ships, you cannot update the copies already on people’s phones. So most changes must be additive: old clients keep working because nothing they rely on moved.
| Change | Breaks old clients? |
|---|---|
| Add a new endpoint | No |
| Add a field to a response | No, if clients ignore fields they do not know |
| Add an optional query parameter | No |
| Remove or rename a response field | Yes |
| Change a field's type, e.g. id from number to string | Yes |
| Make an optional request field required | Yes |
| Change what an existing status code means | Yes |
When a breaking change is worth it, give clients a way to ask for the old behaviour and a deadline to move. Three common places to put the version:
/v2 tends to arrive rarely and all at once.Accept: application/vnd.example.v2+json or a custom Api-Version: 2. Harder to try in a browser, and caches must vary on the header.Stripe-Version header can override it. Each date adds a few changes, and the server translates old requests.Whichever you pick, the default matters more: a request with no version should get the version that client was built against (or the oldest supported one), never silently the newest.
06 Errors a client can act on
A client handles errors in code, so the body needs a stable shape, not a sentence that changes with each release. Use the status code for the category and a machine-readable field for the exact cause. RFC 9457 ("problem details") defines a standard shape with the media type application/problem+json:
The client switches on type (or on your own code field if you roll your own) and shows detail to a person. Field-level validation errors fit as an extra array, for example "errors": [{ "field": "email", "message": "must contain @" }]. Whatever the shape, use the same one on every endpoint.
07 When it bites
GET /posts/42/likeA GET that changes dataPrefetchers, crawlers and caches treat GET as safe and may send it without a click. Anything that writes uses POST, PUT, PATCH or DELETE.GET /postsA list with no default limitFine with 50 rows, an outage with 5 million. Always apply a default page size and a maximum, even when the client sends none.?offset=100000Deep offsetsEach deep page re-reads every skipped row. Use a cursor for feeds and infinite scroll; keep offset for small admin tables where jumping to a page matters.200 OK {"error": "not found"}Errors with a success codeMonitoring counts it as a success, caches may store it, and clients must parse every body to find failures. Send the real status."id": 7 → "id": "7"A quiet type changeA typed client fails to decode the response and the app crashes for everyone on the old version. Treat it as a breaking change.PATCH is not idempotent unless you make it so. {"stock": 5} is safe to repeat; an operation like "add 1 to stock" applied twice adds 2. If a client may retry a write, design the body as the final value or accept an idempotency key.