Skip to content

Designing REST endpoints

Working knowledgeConcept

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.

Actions in the URL
GET /getUser?id=7
POST /createUser
POST /updateUserEmail
GET /deleteUser?id=7
GET /getPostsForUser?id=7
Resources + methods
GET /users/7
POST /users
PATCH /users/7
DELETE /users/7
GET /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.

The five methods on a collection and an item
MethodOn /usersOn /users/7SafeIdempotent
GETList usersRead user 7YesYes
POSTCreate a user(rarely used)NoNo
PUT(rarely used)Replace user 7 with the bodyNoYes
PATCH(rarely used)Change some fields of user 7NoNot by default
DELETE(rarely used)Remove user 7NoYes
  • Safe means the request changes nothing on the server. Link prefetchers and crawlers follow GET links on their own, which is why GET /deleteUser?id=7 above is a real bug and not just ugly.
  • Idempotent means sending it twice has the same effect as sending it once. DELETE /users/7 twice still leaves user 7 gone (the second call may answer 404, but the state is the same). Clients and proxies may retry idempotent requests after a timeout.
  • POST /users twice makes two users. If a client must retry a create, accept an Idempotency-Key header 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:

HTTP
GET /posts?author=7&status=published&sort=-created_at&limit=20

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.

Offset pagination while someone posts
Step 1 of 4
posts table, newest first
p9p8p7p6p5p4p3p2p1
Posts the client has shown
Empty
  • 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.

3 page size

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.

Cursor pagination, same posts
Step 1 of 4
Cursor none
posts table, newest first
p9p8p7p6p5p4p3p2p1
Posts the client has shown
Empty
  • 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.

3 page size
pages.sql
-- offset: the database walks past 3 rows to throw them away
SELECT id, title FROM posts ORDER BY id DESC LIMIT 3 OFFSET 3;
-- cursor: an index on id jumps straight to the first row below 7
SELECT id, title FROM posts WHERE id < 7 ORDER BY id DESC LIMIT 3;

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:

JSON
{
"items": [
{ "id": 9, "title": "..." },
{ "id": 8, "title": "..." },
{ "id": 7, "title": "..." }
],
"next_cursor": "7"
}
OFFSET 100000 LIMIT 20Reads 100,020 rowsThe database still finds and discards every skipped row, so deep pages get slower, and inserts shift the pages under the reader.
WHERE id < cursor LIMIT 20Reads about 20 rowsWith an index on the sort key, every page costs the same, and new rows cannot shift it. The price: no "jump to page 37".

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.

Which changes break a client
ChangeBreaks old clients?
Add a new endpointNo
Add a field to a responseNo, if clients ignore fields they do not know
Add an optional query parameterNo
Remove or rename a response fieldYes
Change a field's type, e.g. id from number to stringYes
Make an optional request field requiredYes
Change what an existing status code meansYes

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:

In the path: /v2/usersEasy to seeShows in logs, links and browser tests. Usually means whole-API versions, so /v2 tends to arrive rarely and all at once.
In a headerClean URLsFor example 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.
Dated versionsSmall stepsStripe’s API is a known example: each account is pinned to a dated version, and a 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:

HTTP
HTTP/1.1 409 Conflict
Content-Type: application/problem+json
{
"type": "https://api.example.com/errors/email-taken",
"title": "Email already registered",
"status": 409,
"detail": "ana@example.com belongs to another account.",
"instance": "/users"
}

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.

08 Check yourself

Question

A feed uses ?limit=20&offset=20. Between page 1 and page 2, two new posts are published at the top. What does the reader see on page 2?

Question

A client times out on a request and retries it. Which request is safe to retry without extra care?

Question

Which change can you ship without a new API version?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?