Skip to content

No. 45API10 min read2,561 words

REST API design: best practices for APIs that last

REST API design best practices for teams who need an API to survive years of change: resources, status codes, errors, pagination, versioning and idempotency.

Written by
Lazy Devs
Published
Updated
Sources
Cited inline

Key takeaways ยท 05

The short version

  1. 01Model resources and their state (PATCH /users/42 with a status field) before inventing action endpoints; resource URLs absorb new requirements without new routes.
  2. 02Return honest HTTP status codes and a stable, machine-readable error body with a code field clients can branch on. RFC 9457 Problem Details is a good default shape.
  3. 03Use cursor (keyset) pagination sorted on a unique tuple like (created_at, id); offset pagination gets slower with depth and skips or duplicates rows when data changes.
  4. 04Version in the URL prefix, keep the version layer a thin request and response transform over one shared core, and never bump the version for additive changes.
  5. 05Make every create and payment-like POST safe to retry with an Idempotency-Key header, and keep the contract in an OpenAPI spec that CI checks against real responses.
On this page ยท 12

A REST API lasts when it is predictable: it models resources rather than actions, returns honest HTTP status codes, gives errors one stable machine-readable shape, paginates with cursors, makes writes safe to retry, and versions only at the edge. Most APIs do not die from a single bad decision. They die from a hundred small ones that nobody could undo, because by the time anyone noticed, three mobile apps and a partner integration already depended on the mess.

The goal is not cleverness. It is being boring in a way that still works five years from now. These are the rules we follow when we design APIs in our API and backend engineering work, with the reasoning behind each call.

Model resources, not actions

The biggest predictor of an API aging well is whether it describes nouns or verbs. A URL like /users/42/deactivate feels natural when you write it, but it pins your design to one specific action. Six months later you need "deactivate but keep the subscription", and now you are inventing /users/42/soft-deactivate and the surface area starts to rot.

Model state instead. A user has a status. You change it.

PATCH /users/42
Content-Type: application/json
 
{ "status": "deactivated" }

This pays off because the same endpoint absorbs new fields without new routes. When you genuinely have an operation that is not a state change (sending an email, triggering a re-index, refunding a payment), a verb endpoint such as POST /payments/123/refunds or POST /reports/42/exports is fine and honest. Notice that even those are usually better expressed as creating a sub-resource: a refund or an export is a thing with its own ID and status that a client can poll. The rule is not "never use verbs", it is "reach for resources first and notice when you are fighting them".

Naming conventions that save arguments later

Decide these once, write them down, and enforce them in review:

  • Plural nouns for collections: /invoices, /invoices/inv_123.
  • One casing everywhere: pick snake_case or camelCase for JSON fields and never mix them.
  • Prefixed, opaque IDs: inv_8f3k2 tells a support engineer what kind of object they are looking at and stops clients doing arithmetic on sequential integers.
  • Shallow nesting: /customers/42/invoices is fine; /customers/42/invoices/7/lines/3/taxes is a sign the child should be a top-level resource with a filter.
  • Timestamps in ISO 8601 UTC: "2026-04-18T09:30:00Z", never local time and never a bare Unix integer in one place and a string in another.

Use HTTP methods the way the spec defines them

RFC 9110, the current HTTP semantics specification, defines which methods are safe (no side effects) and which are idempotent (repeating them has the same effect as doing it once). Caches, proxies, browsers and retry libraries all rely on those definitions, so breaking them breaks infrastructure you do not control.

MethodUse it forSafeIdempotentTypical success code
GETReading a resource or collectionYesYes200
POSTCreating a resource, or a non-idempotent operationNoNo201 with Location, or 202
PUTReplacing a resource entirelyNoYes200 or 204
PATCHPartially updating a resourceNoNot by default200
DELETERemoving a resourceNoYes204

The practical consequence: never change data on a GET. Link prefetchers, crawlers and monitoring tools will happily call it. And because POST is not idempotent, a client that times out and retries can create a duplicate, which is why the idempotency section below matters.

Pick status codes that tell the truth

A surprising number of APIs return 200 OK with { "error": "not found" } in the body. This forces every client to parse the body to know if the request worked, which means your monitoring, your CDN and your retry logic are all blind. Use the protocol that already exists:

  • 200 for a successful read or update.
  • 201 for a created resource, with a Location header pointing at it.
  • 202 when you accepted work that will finish later, such as an export handled by a background job.
  • 204 for a success with nothing to return, such as a delete.
  • 400 for malformed input the client can fix.
  • 401 for "we do not know who you are", 403 for "we know, and no".
  • 404 when the resource does not exist (or when you do not want to admit it exists, for that user).
  • 409 for conflicts, like a duplicate unique field or a stale update.
  • 422 when the body parsed fine but failed business validation.
  • 429 when they hit a rate limit, with a Retry-After header.
  • 500 for your bugs, 503 for "temporarily unavailable, try again".

The 403 versus 404 choice matters more than people think. A 403 on a record the caller cannot see confirms the record exists. Returning 404 to a logged-in user who lacks access is often the safer choice, because it does not leak that the ID is real. This is the class of bug OWASP's API Security Top 10 lists first: broken object-level authorization, where an API checks that you are logged in but not that the object is yours.

Make error bodies machine-readable

Humans read your error messages once, during development. Code reads them on every failed request, forever. Give errors a stable shape with a code clients can branch on, not just a string they have to pattern-match.

RFC 9457, Problem Details for HTTP APIs, standardises exactly this, and it is a sensible default unless you already have a house format:

{
  "type": "https://api.example.com/errors/email-already-taken",
  "title": "Email already registered",
  "status": 409,
  "detail": "That email is already registered.",
  "code": "email_already_taken",
  "errors": [{ "field": "email", "code": "taken" }]
}

The code (or type) is a contract. The human-readable message is for your logs and the occasional developer. Never make a client write if (msg.includes("already")), because the day someone fixes a typo in that string, their integration breaks and you will both spend an afternoon finding out why.

Three habits that make errors genuinely useful:

  1. Return every validation error at once, keyed by field, so a form can highlight all of them in one round trip.
  2. Include a request ID in a response header and in your logs, so a customer can paste it into a support ticket and you can find the exact trace. Structured logs with that ID attached turn a vague complaint into a five-minute fix.
  3. Never leak internals. Stack traces, SQL fragments and library error messages belong in logs, not in a 500 response body.

Pagination: cursors, not page numbers

Offset pagination (?page=3&limit=20) is the default everyone copies, and it breaks in two ways. It gets slower the deeper you go, because the database still has to walk and discard every row before the offset (a cost no amount of database indexing removes). And it skips or duplicates records when items are inserted or deleted between requests: if a user signs up while someone is paging through, the page boundaries shift under them.

Cursor pagination, also called keyset pagination, fixes both. You sort by something stable and unique, then ask for "everything after this point".

-- First page
SELECT id, email, created_at
FROM users
ORDER BY created_at DESC, id DESC
LIMIT 21;  -- fetch one extra to know if there is a next page
 
-- Next page, using the last row from the previous response as the cursor
SELECT id, email, created_at
FROM users
WHERE (created_at, id) < ($1, $2)
ORDER BY created_at DESC, id DESC
LIMIT 21;

The (created_at, id) tuple comparison is the part people miss. Sorting by a timestamp alone is not deterministic when two rows share the same value, so you add the primary key as a tiebreaker. Back it with a composite index on (created_at DESC, id DESC) and every page costs the same, whether it is the first or the ten-thousandth. Encode the cursor (base64 the created_at and id) so clients treat it as opaque and you keep the freedom to change what is inside it.

A clean response wraps the data and the cursor together:

{
  "data": [],
  "page": { "next_cursor": "MjAyNi0wNC0xOFQ...", "has_more": true }
}
Offset paginationCursor pagination
Deep page performanceDegrades with depthConstant with the right index
Consistency during writesSkips or repeats rowsStable
Jump to page NEasyNot supported
Total countNatural, but expensive on big tablesSeparate, optional query
Best forSmall admin listsFeeds, logs, any large or growing collection

Make writes safe to retry with idempotency keys

Networks fail in the worst possible place: after the server committed the write, before the client got the response. The client retries, and now there are two orders, two charges, two welcome emails.

The fix is an idempotency key. The client generates a unique key per logical operation and sends it in a header. The server stores the key alongside the result of the first request and, for any repeat with the same key, returns the stored result instead of doing the work again. Stripe's idempotent requests are the best-known implementation, and the IETF has an Idempotency-Key header draft that formalises the pattern.

POST /v1/orders
Idempotency-Key: 6c1b9a0e-3f4e-4c1a-9e2b-7d8f0a1b2c3d
Content-Type: application/json
 
{ "cart_id": "cart_91x", "payment_method": "pm_4k2" }

Implementation details that matter:

  • Store the key with a unique constraint and a hash of the request body. A reused key with a different body is a client bug: reject it with 422.
  • Handle the race where two identical requests arrive at once. Insert the key first, inside the same transaction as the work, so the second request hits the unique constraint and waits or gets a 409.
  • Expire keys after a sensible window, such as 24 hours. Retries come within minutes, not weeks.

The same principle protects the other direction: when you send events to other systems, receivers need to deduplicate too, which we cover in webhooks done right.

Version at the edge, not everywhere

Versioning is where good intentions go to die. The trap is sprinkling if (version >= 2) checks through your business logic until no one can safely delete anything.

Put the version in the URL prefix (/v1/, /v2/) because it is visible in logs, easy to route, and trivial to explain to a partner over email. Header-based versioning is more "correct" in REST purist terms, but it is invisible in a browser and harder to debug. Pick visible over pure. The exception is a large public API with many integrators: there, date-based versions pinned per account, as Stripe does, let you ship small breaking changes continuously, but that model needs real tooling behind it.

Then keep the version boundary thin. Your /v1 and /v2 handlers should both call the same core service and differ only in how they shape the request and response. A small transformation layer per version is cheap to maintain. Branching logic scattered through your data layer is not.

And resist minting a new version for additive changes. Adding an optional field or a new endpoint does not break anyone, so it does not need /v2. Reserve version bumps for changes that genuinely break existing clients.

ChangeBreaking?What to do
Add an optional request fieldNoShip it
Add a response fieldNo, if clients ignore unknown fieldsShip it, and tell clients to ignore unknowns
Add a new enum valueOften, yesAnnounce it, or treat enums as open from day one
Rename or remove a fieldYesNew version, or keep both during a deprecation window
Change a field's type or meaningYesNew field with a new name
Make an optional field requiredYesNew version

When you do retire something, say so in the response itself. The Deprecation and Sunset headers, plus a dated email to every key that still calls the old endpoint, give integrators time to move.

Treat the contract as the product

The endpoints are the easy part. What clients actually depend on is the shape of your data, and that is where discipline pays off.

Never repurpose a field. If status returned "active" and "inactive" and you now need a third state, add it as a new value, and know that a client which built a boolean toggle on those two values will break. That is why the table above treats new enum values as potentially breaking.

Be conservative about what you remove and liberal about what you accept. Ignore unknown fields in request bodies instead of rejecting them, so an older client sending a slightly different payload still works. Keep null versus absent meaningful and consistent: decide whether a missing field means "unchanged" or "set to null" in a PATCH, document it, and never flip it.

Write the contract down somewhere executable. An OpenAPI specification that generates your client types and gets checked in CI against real responses catches the drift between "what the docs say" and "what the server actually sends" before your users do. If your clients are mostly your own frontends with very different data needs, it is also worth reading when GraphQL is the right call before you design dozens of bespoke endpoints.

Common REST API design mistakes we fix

When we take over an existing API, the problems are rarely exotic. They are the same handful, and each one is cheaper to avoid than to unwind:

  • Leaking the database schema. Column names, join tables and internal flags exposed one-to-one as JSON. The first migration becomes a breaking change.
  • Authorization checked only at the route. The handler checks "is logged in" but not "owns this invoice". This is the most common serious API vulnerability, and the fix is an ownership check on every single object lookup.
  • Unbounded list endpoints. GET /orders returns every order ever, until the day it times out.
  • Inconsistent errors. Three different error shapes from three different eras of the codebase.
  • No retries considered. Creates that duplicate on timeout because nobody thought about idempotency.
  • Versioning by branching. if (apiVersion === 2) in the data layer.

A REST API design checklist

Before a new endpoint ships, check it against the rules above:

  • Resources are nouns, actions are HTTP methods, and names follow one convention.
  • GET never changes state; PUT and DELETE are safe to repeat.
  • Status codes tell the truth, and every error uses the same machine-readable body.
  • Every object lookup checks ownership, not just "is logged in".
  • List endpoints are paginated with cursors and have a maximum page size.
  • Creates and payments accept an idempotency key.
  • The response shape is a deliberate contract, not the database schema.
  • Breaking changes go through a new version at the edge, with a deprecation date for the old one.
  • Rate limits are in place and documented.

Build an API your clients will not have to work around

None of this is exciting, and that is exactly the point. Model resources, use methods and status codes the way HTTP defines them, give errors one machine-readable shape, paginate with cursors, make writes idempotent, version at the edge, and guard the data contract like it is the real product, because to your clients it is. The good kind of lazy is the design you do not have to keep apologising for.

If you are planning a new API, or staring at one that already went sideways, we design and rebuild them as part of our API development work. Tell us what you are building and we will tell you honestly where we would start.

FAQ ยท 05 questions

Frequently asked questions

What makes a REST API well designed?

A well-designed REST API is predictable. It names resources consistently, uses HTTP methods and status codes as the HTTP specification defines them, returns errors in one stable shape, paginates large collections, and changes without breaking existing clients. Predictability matters more than strict REST purity.

Should I put the API version in the URL or in a header?

For most teams the URL prefix, such as /v1/, is the better choice. It shows up in logs, is easy to route at a gateway, and is obvious to partners reading an email or a curl command. Header or date-based versioning works well too, but it needs tooling and discipline to stay debuggable.

What is the difference between PUT and PATCH?

PUT replaces the whole resource with the representation you send, so fields you omit are reset. PATCH applies a partial update, changing only the fields you include. Most product APIs want PATCH for updates, with a documented rule for whether a null value clears a field.

Is offset pagination ever fine?

Yes, for small, rarely changing collections such as an admin list of a few hundred settings, or when users genuinely need to jump to page 7. For feeds, activity logs and anything large or frequently written, cursor pagination is faster and does not skip or repeat items.

How do I make a POST request safe to retry?

Accept an Idempotency-Key header generated by the client, store the key with the result of the first request, and return that stored result for any repeat with the same key. Reject a reused key that arrives with a different request body. This is how payment APIs like Stripe avoid double charges on network retries.

Related service

API & Backend Engineering

Secure, well-documented APIs that scale.

Learn more

Next step

Want this built right?

This is the work we do every day. Tell us what you are building and we will show you exactly how we would ship it.

First reply
Within 1 business day
Typical start
1โ€“2 weeks
Pricing
Fixed price per phase
You own
All code and accounts