All articles
165 articles · updated weekly See our Tools
All articles
All

REST API best practices: design, versioning and errors

REST API best practices grounded in the RFCs: resources, PUT vs PATCH, status codes, RFC 9457 errors, idempotency keys, cursor pagination and versioning.

REST API best practices: design, versioning and errors
COVER · All

A partner sent POST /payments, the gateway timed out after 30 seconds, their HTTP client retried on its own, and the end customer was charged twice. The same day, another integrator opened a ticket because our API returned 200 OK with {"error": "not found"} in the body, so their retry logic never fired. Neither bug was in the business code. Both were in the HTTP contract, in decisions nobody made explicitly when the API was born.

This post is about those decisions: the REST API best practices I enforce in code review, each one tied to the RFC behind it, with real requests and responses. If you're still on the concept, start with what an API is; if you're choosing a style, GraphQL vs REST covers the comparison.

The short version: what a well-built REST API does

If you only have two minutes, this is it. The rest of the post explains the why and shows the exact format of each item.

  1. URLs identify resources (plural nouns); the HTTP method carries the action.
  2. Every method follows RFC 9110 semantics: GET is safe, PUT and DELETE are idempotent, POST is not.
  3. The status code tells the truth. An error never comes back as 200.
  4. Every error has the same shape: Problem Details (RFC 9457), application/problem+json.
  5. A POST with a critical side effect (payment, sending email) accepts an Idempotency-Key.
  6. Concurrent updates use ETag + If-Match, not "last write wins".
  7. Every list is paginated, preferably with a cursor.
  8. A breaking change ships as a new version, and the old one is retired with the Deprecation and Sunset headers.
  9. Credentials go in the Authorization header, never in the URL; authorization is checked per object, not just per route.
  10. The contract is written down (OpenAPI) and tested.

Resources and URLs: nouns, plural, shallow hierarchy

The classic mistake is treating the URL as a function call: GET /getUsers, POST /createUser, POST /deleteUser?id=42. REST is not RPC. The URL identifies the resource; the verb is already in the method:

GET    /users          list
POST   /users          create
GET    /users/42       read one
PUT    /users/42       replace
PATCH  /users/42       change part
DELETE /users/42       remove

Three rules that end PR debates:

Always plural. /users and /users/42, never /user/42 on one endpoint and /orders on the next. Naming inconsistency is the first thing integrators get wrong.

Nest only for real ownership, and at most one level. /users/42/orders makes sense because the order belongs to the user. /users/42/orders/18/items/3 doesn't: the item already has its own identity, so /order-items/3 or /orders/18/items with a filter does the job.

Non-CRUD actions are the exception, and explicit. POST /orders/18/cancel is legitimate when cancelling triggers a refund, an email and a deadline rule, that is, when it isn't just flipping a field. If it is just status = "cancelled", it's a PATCH.

And pick one field naming convention (snake_case or camelCase) and one date format (ISO 8601 with offset, 2026-11-08T14:30:00Z) for the whole API. Nobody remembers the rule; everybody remembers the exception.

HTTP methods: safe, idempotent, and PUT vs PATCH

RFC 9110 defines two properties people mix up. Safe means essentially read-only: GET, HEAD, OPTIONS. Idempotent means several identical requests have the same intended effect as a single one: the safe methods, plus PUT and DELETE. Idempotent does not mean "no side effects". DELETE /users/42 deletes the user, and deleting twice leaves the system in the same state as deleting once (the second response may be 404, and that's fine: the RFC talks about effect, not identical responses).

This matters because the RFC itself says a client may automatically retry an idempotent request if the connection drops before the response, and should not automatically retry a non-idempotent one. That's exactly the double-charge bug from the opening: the client treated POST as safe to retry.

PUT vs PATCH. PUT replaces the whole resource with the representation sent: an omitted field is a deleted field (or an error, if it's required). PATCH, defined in RFC 5789, applies a partial change and is not idempotent by definition. The simplest body format is JSON Merge Patch (RFC 7396), where null removes a field and arrays are replaced whole:

PATCH /users/42 HTTP/1.1
Content-Type: application/merge-patch+json

{ "phone": null, "name": "Ana Souza" }

In practice: PATCH with merge patch for edit forms; PUT when the client really holds the whole document (settings, an exported profile).

A POST that creates responds 201 with Location. RFC 9110 says the created resource is identified by the Location header. It saves the client from guessing the URL:

HTTP/1.1 201 Created
Location: /users/43
Content-Type: application/json

{ "id": 43, "name": "Ana Souza", "created_at": "2026-11-08T14:30:00Z" }

REST API status codes: the right vocabulary

The IANA registry has dozens of codes; a business API uses about fifteen. The names below are the official ones from RFC 9110 (and RFC 6585 for 428 and 429):

Status When to use it
200 OK Success with a body (GET, PATCH that returns the resource)
201 Created Resource created; send Location
202 Accepted Accepted for asynchronous processing
204 No Content Success with no body (DELETE, PUT with no return)
400 Bad Request Malformed request: broken JSON, wrong parameter type
401 Unauthorized No valid credentials; requires WWW-Authenticate
403 Forbidden Valid credentials, but no permission
404 Not Found Resource doesn't exist (or you don't want to reveal that it does)
409 Conflict Conflict with current state (email already registered, invalid transition)
412 Precondition Failed If-Match didn't match: someone changed it first
415 Unsupported Media Type A Content-Type the API doesn't accept
422 Unprocessable Content Correct syntax, semantically invalid content
428 Precondition Required The API requires a conditional request (If-Match)
429 Too Many Requests Rate limit; send Retry-After
500 / 503 Server failure / temporarily unavailable

Note 422 Unprocessable Content. A lot of material still says "Unprocessable Entity", the name from RFC 4918 (WebDAV); RFC 9110 promoted the code to general HTTP under the new name. The practical rule I use: JSON that doesn't parse or a field with the wrong type is 400; valid JSON that breaks a business rule (end date before start date, a tax ID with a bad check digit) is 422. Payload validation itself, with a schema, is covered in JSON Schema for REST APIs.

401 vs 403 trips up even senior devs. 401 is "I don't know who you are": the credential is missing or invalid, and RFC 9110 says the server must send WWW-Authenticate with a challenge (for tokens, WWW-Authenticate: Bearer). 403 is "I know who you are and the answer is no"; retrying with the same credential won't help. And the RFC explicitly allows answering 404 instead of 403 when you don't want to confirm the resource exists, which is the right behavior for GET /invoices/9876 belonging to another customer.

429 comes with Retry-After, in seconds or as an HTTP-date. Without it, each client invents its own backoff, and usually gets it wrong:

HTTP/1.1 429 Too Many Requests
Retry-After: 30
Content-Type: application/problem+json

Error bodies: use Problem Details (RFC 9457)

The right status code is necessary, but the client also needs a body it can handle without parsing a message string. Don't invent a format: RFC 9457, from July 2023, defines Problem Details for HTTP APIs and obsoletes RFC 7807. The media type is application/problem+json and the standard members are type, title, status, detail and instance. A complete validation error looks like this:

HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json

{
  "type": "https://api.example.com/problems/validation-error",
  "title": "Invalid input data",
  "status": 422,
  "detail": "2 fields failed validation.",
  "instance": "/users",
  "request_id": "req_7f3a9c",
  "errors": [
    { "pointer": "#/email", "detail": "Invalid email format." },
    { "pointer": "#/birth_date", "detail": "Date is in the future." }
  ]
}

What each part does:

  • type is the stable identifier of the problem type, a URI that ideally points to documentation. That's what the client switches on, not title. If omitted, it defaults to about:blank, and then title should just be the status phrase.
  • title is the human-readable summary of the type, the same for every occurrence; detail explains this occurrence.
  • status repeats the HTTP code, useful when the body gets logged far from the response.
  • request_id and errors are extension members, which the RFC allows. RFC 9457 itself shows an errors array with a pointer (JSON Pointer) for validation errors; that's what lets the frontend highlight the right field.

Two production rules: never return a stack trace or a raw database exception message, and always return a request identifier you can find in the logs.

Idempotency-Key: safe retries for POST

The double-charge bug has a standard solution on the way. The client generates a unique key per operation and sends it in a header; the server stores the first response for that key and replays it on repeats, without executing again:

POST /payments HTTP/1.1
Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324"
Content-Type: application/json

{ "order_id": 18, "amount_cents": 15990 }

The header is specified in draft-ietf-httpapi-idempotency-key-header, from the IETF HTTPAPI working group. Mind the status: as of November 2026 it is an active Internet-Draft (version 08), not an RFC, so details may still change. What the draft recommends today: the value is a Structured Field String (hence the quotes), a key reused with a different payload gets 422, a key whose first request is still processing gets 409, and an operation that requires the key but didn't receive one responds 400. A client-generated UUID v4 works well as the key; store key and response with an expiry (24 hours is common) and document that window.

Concurrency: ETag and If-Match against lost updates

Two support agents open the same record, both save, and the first one's change silently disappears. That's the "lost update", and HTTP solves it with conditional requests. The GET returns an ETag (the validator that the post on browser caching with Cache-Control and ETag explains from the browser side); the write sends that value in If-Match:

PATCH /users/42 HTTP/1.1
If-Match: "v17"
Content-Type: application/merge-patch+json

{ "name": "Ana Souza" }

If the resource changed since it was read, the response is 412 Precondition Failed and the client reloads before overwriting. If you want to force every client to do this, answer 428 Precondition Required to writes without If-Match; RFC 6585 cites the lost update problem as the reason for that code.

Pagination: cursor vs offset (and filters)

An unpaginated list is the decision that looks harmless on day zero and becomes a 40 MB response six months later. Paginate from the very first endpoint, with a server-side maximum.

Offset (?page=3&per_page=20 or ?offset=40&limit=20) is simple and lets you jump to page N. It has two problems: the database has to walk and discard every row before the offset, so page 5,000 is slow; and if records are inserted or deleted while the client pages through, it sees duplicates or skips items.

Cursor (keyset) uses the position of the last item seen, typically the sort key, encoded into an opaque value. The query becomes WHERE id > :last ORDER BY id LIMIT 20, which uses an index and doesn't suffer from inserts in the middle. The cost: you can't jump to page 5.

GET /orders?status=pending&sort=-created_at&limit=20&cursor=eyJpZCI6MTIwfQ HTTP/1.1
{
  "data": [ { "id": 121, "status": "pending" } ],
  "next_cursor": "eyJpZCI6MTQwfQ",
  "has_more": true
}

My rule: cursor for feeds, history and any large table; offset only for a small admin screen where "go to page 7" is a requirement. Treat the cursor as opaque to the client (base64 isn't encryption, so put nothing sensitive in it), and don't return total by default: COUNT(*) on a big table costs more than the page itself. If the sort isn't on a unique key, add the ID as a tiebreaker, or the cursor will skip records sharing a timestamp. This is where a time-ordered ID helps, the subject of UUID v4 vs UUID v7.

For filters, use the query string with real field names (?status=pending&created_after=2026-01-01) and a single sort syntax (sort=-created_at,name) across the whole API.

Versioning and deprecation: Deprecation and Sunset

Before choosing a version format, know what requires a new version. Adding an optional response field or a new endpoint is compatible, as long as clients ignore unknown fields (document that they must). Removing or renaming a field, changing a type ("id": "42" to 42), making an input field required, or changing what a status means is a break.

Format: a version in the path (/v1/users) is what I use and recommend for public APIs, because it's visible in logs, easy to route at the gateway and impossible to forget. Header versioning (Api-Version: 2) or media type versioning (Accept: application/vnd.example.v2+json) keeps the URL clean but complicates caching (it needs Vary), manual testing and docs. Any of them works; mixing them doesn't.

What changed recently is retirement. Since March 2025 there's RFC 9745, which standardizes the Deprecation header, and it pairs with Sunset from RFC 8594, which says when the resource is expected to stop responding:

HTTP/1.1 200 OK
Deprecation: @1798761599
Sunset: Wed, 30 Jun 2027 23:59:59 GMT
Link: <https://api.example.com/docs/migrate-v2>; rel="deprecation"; type="text/html"

(Example dates.) Note the different formats: Deprecation is a Structured Field Date, @ followed by seconds since the Unix epoch (the value above is 2026-12-31 23:59:59 UTC), while Sunset is an HTTP-date. RFC 9745 requires Sunset not to be earlier than Deprecation, and registers the rel="deprecation" link relation to point at migration docs. For a public API, I wouldn't retire anything with less than six months between the two, and I'd monitor who still calls the old version before switching it off.

Baseline security that isn't optional

  • HTTPS everywhere, including any exposed staging environment.
  • Credentials in the header: Authorization: Bearer <token> (RFC 6750). GET /users?api_key=abc123 leaks the key into proxy logs, browser history and the Referer header. How the token is issued and validated is covered in how JWT works and OAuth 2.0 explained.
  • Per-object authorization. The first item of the OWASP API Security Top 10 2023 is Broken Object Level Authorization: an authenticated user swaps /invoices/9876 for /invoices/9877 and sees another customer's invoice. Checking "is logged in" on the route isn't enough; every query has to filter by owner.
  • Don't accept fields the client shouldn't set. If the PATCH body goes straight into the ORM, someone sends "role": "admin". Use an explicit list of writable fields.
  • Rate limiting with 429 and Retry-After, plus limits on payload size and on the pagination limit.
  • CORS with explicit origins; Access-Control-Allow-Origin: * only for a truly public API without cookies.

Documentation and contract: OpenAPI and tests

An API without a written contract is documented in Slack. Describe endpoints, schemas and errors in OpenAPI; since version 3.1, OpenAPI uses JSON Schema 2020-12 for schemas, so the same schema that validates the payload on the server describes the contract for the client. Also document the problem types (every Problem Details type), the rate limits and the deprecation policy.

Docs describe; tests guarantee. Validating real responses against the contract in CI catches the renamed field before the partner does. The post on contract testing between services shows how to do that without building a giant E2E suite, and automated API testing covers the rest of the pyramid. And if your problem is telling the client when something happens, instead of them asking, that's a different pattern: webhooks.

Frequently asked questions

What's the difference between REST and RESTful? Does my API need HATEOAS?

REST is the architectural style Roy Fielding described in his 2000 dissertation, with the constraints client-server, stateless, cache, uniform interface, layered system and code-on-demand (optional). "Hypermedia as the engine of application state" (HATEOAS) is part of the uniform interface, and Fielding wrote in 2008 that an API not driven by hypertext is not REST. By the strict definition, almost no "REST API" out there is REST. In practice, navigation links help with pagination and state flows, but their absence isn't what breaks integrations; the items in this post are.

Should I use 400 or 422 for validation errors?

Use 400 when the request can't even be interpreted (invalid JSON, wrong type, missing required parameter) and 422 Unprocessable Content when it's syntactically correct but breaks a business rule. Many APIs use 400 for everything, and that's acceptable if it's consistent and the Problem Details body says which field failed. The mistake is mixing them without a rule.

How do I version a REST API without breaking clients?

Make only additive changes to the current version and require clients to ignore unknown fields. When a break is unavoidable, ship the new version side by side, mark the old one with Deprecation, Sunset and Link rel="deprecation", track who still uses it, and turn it off only after the announced date.

REST or GraphQL?

REST is the sensible default for most APIs: HTTP caching, status codes and mature tooling. GraphQL pays off when many different clients need very different slices of the same data. The full comparison, including caching and N+1 costs, is in GraphQL vs REST.

A good API is one the integrator never has to ask about

Almost everything in this post has a written standard: method and status semantics in RFC 9110, errors in RFC 9457, deprecation in RFCs 9745 and 8594, safe retries in an IETF draft still in progress. Following the standard isn't purism; it spares the client from learning your exceptions. Before publishing an endpoint, run through the list at the top; items 3 and 5 alone would have prevented both incidents this post opened with.

The editorial content ends here. When I'm unsure which code fits (412 or 409? 422 or 400?), I check the HTTP status codes reference on Quick Tools, which summarizes each one's semantics; and to check an error body or a payload against the contract's schema, the JSON Schema validator.

RD
Author
Rafael Duarte
Backend developer with a background in fintech and B2B SaaS — worked on teams that scaled APIs from zero to millions of requests. Carries enough production scars to hold strong opinions on tools, patterns and architecture decisions. Not an academic: he read the UUID RFC when he had to choose between v4 and v7 for a write-heavy table.
View profile