REST API Design Best Practices: Resource Modelling, Idempotency, and Versioning

An API Is a Product, Not a Mirror of Your Database

Expose every table as a CRUD endpoint and you end up with /getUsers, /createOrder, /updateUserStatus. It runs, but every client needs its own glue and every schema change must be announced to every consumer.

The value of REST is not tidiness. It is that an endpoint can be guessed correctly without reading the docs — which starts with resource modelling, not URL strings.

1. Resource Modelling: Organise URLs Around Nouns

Use nouns, not verbs

The URL names the resource; the method names the action. A verb in the URL throws away the semantic layer HTTP already provides.

Anti-pattern Preferred Why
GET /getUsers GET /users GET already means read
POST /createOrder POST /orders POST already means create
POST /deleteUser/123 DELETE /users/123 Otherwise intermediaries cannot see it is destructive
GET /getUserOrders?uid=1 GET /users/1/orders Hierarchy belongs in the path

Express hierarchy, but stop at two levels

/users/1/orders/2/items/3 is legal but locks clients into one traversal path and forces a parent check at every level. Rules:

  • Use hierarchy when the relationship is exclusive: /users/1/orders;
  • Flatten past two levels and filter with query parameters: /orders?userId=1&status=paid;
  • Let a globally unique id be a top-level resource: /orders/2, without forcing entry through the parent.

Naming consistency

  • Plural nouns for collections: /orders, /users;
  • Lowercase only. Parts of a URL are case-sensitive, so /orderItems and /orderitems can become two resources;
  • Hyphens for multi-word segments: /order-items, no escaping needed;
  • No trailing slash. Some frameworks treat /orders and /orders/ as separate routes.

Non-CRUD actions

Publish, cancel and batch-recalculate do not map onto CRUD. Three options, in priority order:

  1. Model the action as a resource: POST /orders/1/cancellations — cancelling becomes creating a cancellation record, which is auditable;
  2. Model it as a state field: PATCH /orders/1 with { "status": "cancelled" };
  3. Verb suffix as a last resort: POST /orders/1:publish, acceptable but document that it is not a resource.

2. HTTP Methods: Decide the Retry Semantics First

Method Meaning Safe Idempotent Typical response
GET Read a resource Yes Yes 200 + body
HEAD Headers only Yes Yes 200, no body
POST Create or sub-resource action No No 201 + Location
PUT Full replacement (may create) No Yes 200 / 201 / 204
PATCH Partial update No No by default 200 / 204
DELETE Delete No Yes 204 / 200
OPTIONS Ask which methods are supported Yes Yes 200 + Allow

Full semantics and the side-effect matrix are in the HTTP methods reference.

Idempotency: Which Methods Must Be Idempotent

Idempotent means running the same request N times leaves the same server state as running it once.

By specification, GET/HEAD are safe and idempotent, PUT/DELETE must be idempotent, POST is not, and PATCH depends on the payload. This matters because retries are guaranteed: network handovers, gateway replays, at-least-once queues, double taps.

What actually happens on a retry:

Method Result of the retry Required protection
POST /orders A second order Client sends Idempotency-Key; server deduplicates on it
PATCH { balanceDelta: -100 } Charged twice Send an absolute { balance: 900 } instead
PUT /orders/1 Same result as the first call None — idempotent by nature
DELETE /orders/1 Second call returns 404 None — state still matches one execution
GET /report?refresh=1 Side effects fire twice Do not put side effects behind GET

Making Idempotency-Key work: the client generates the key per business operation, not per HTTP attempt (a fresh key on every retry defeats the purpose); the server stores key → the original status and body and replays it; reusing a key with a different body must return a conflict (409), or one key will mask two different writes; the retention period is a business decision — the original approach here was 24 hours. Generate keys with the UUID generator. Return 201 Created with the new resource URL in Location on success; asynchronous creation returns 202 Accepted with a status endpoint, never 200 pretending the work is done.

3. Status Codes: Layer Them

Returning 200 for everything blinds monitoring, misleads gateway caches, and forces clients to parse the body to learn whether the call worked.

Class Meaning Common codes
2xx Success 200 OK / 201 Created / 202 Accepted / 204 No Content
3xx Redirection and caching 301 / 302 / 304 Not Modified
4xx Client error, retrying is pointless 400 / 401 / 403 / 404 / 409 / 422 / 429
5xx Server error, retry is reasonable 500 / 502 / 503 / 504

The complete list and common misuses are in the HTTP status codes reference. Boundaries that get judged wrong:

  • 400 vs 422: valid syntax with failed semantics (end date before start date) is 422; malformed syntax is 400;
  • 401 vs 403: 401 means we do not know who you are; 403 means we do and the answer is no — an authenticated user without permission gets 403;
  • 404 vs 403: hiding existence with 404 is a legitimate security practice;
  • 409 Conflict: a state conflict (duplicate submission, version mismatch, insufficient stock) that says retrying will not help until the state changes;
  • 429: Retry-After is mandatory, otherwise blind retries turn a rate limit into an avalanche.

4. A Uniform Error Format

Use RFC 7807 application/problem+json as the shared envelope:

{
  "type": "https://api.example.com/errors/order-already-paid",
  "title": "Order already paid",
  "status": 409,
  "detail": "Order 9f3c has already been paid and cannot be modified.",
  "instance": "/orders/9f3c",
  "code": "ORDER_ALREADY_PAID",
  "errors": [
    { "field": "quantity", "reason": "must be greater than 0" }
  ]
}

Four points decide whether the format is usable:

  1. type is the stable contract. Clients branch on it, never on detail prose — prose changes, the URI should not;
  2. code is a deliberate extension for localisation and log aggregation, where the same code groups directly;
  3. errors carries field-level detail. Form endpoints are unusable without it;
  4. No internal leakage: stack traces, SQL, internal hostnames and raw user input have no place in an error body.

To freeze the contract, generate a schema from real responses with the JSON Schema generator — it drifts far less than hand-written docs.

5. Pagination: Where Offset and Cursor Break

Dimension Offset Cursor
Syntax ?offset=100&limit=20 ?cursor=eyJpZCI6MTAwMH0&limit=20
Deep pages Degrades linearly (scan and discard N rows) Constant, index lookup
Concurrent inserts/deletes Duplicates or skips Immune, anchored on the sort key
Random page jumps Supported Not supported
Total count Easy Needs an extra count
Best for Admin, reports Feeds, timelines, exports

Where offset breaks: writes during paging shift the window, so page two can repeat the last row of page one or skip a row; deeper offsets get slower because the database still scans and discards everything before them.

Where cursor breaks: a cursor needs a unique and stable sort key. Sorting by created_at with duplicate timestamps requires a composite cursor with the id, or records sharing a timestamp get skipped or repeated; sorting by a mutable updated_at lets a row move out of the window after an edit; fetching "the row after the last id" breaks when that row is deleted, so use a comparison query such as WHERE (created_at, id) > (…). Treat the cursor as an opaque, validated string — never concatenate it into SQL.

One global convention for filtering and sorting:

?status=paid&created_after=2026-01-01
?sort=-created_at,amount          # leading minus means descending
?fields=id,status,total           # be explicit about its effect on cache keys
?count=true                       # total is the most expensive COUNT(*); never return it by default

For diffing two revisions of a response, JSON Diff beats comparing fields by eye.

6. Versioning

Strategy Example Pros Cons Best for
URL prefix /v1/orders Obvious, shareable, visible in logs Version leaks into the identifier Public APIs
Request header Accept: application/vnd.app.v1+json Clean URLs, proper content negotiation Hides the version, complicates caching Internal services
Query parameter ?version=1 Trivial to implement Pollutes the query space, easily ignored Not recommended

Avoid bumping the version at all. Backward-compatible changes need no new version: new optional request fields, new response fields (provided clients ignore unknown ones), new endpoints, new Link headers or error type values, and new enum values (provided clients tolerate unknown ones).

Breaking changes require a version bump or a staged rollout: removing or renaming a field, tightening validation, changing a field type or unit, changing error semantics. The test is simple — will an un-upgraded client break? If yes, it is breaking.

7. Caching and Conditional Requests

Header Direction Purpose
Cache-Control Response Policy (max-age, no-store, private)
ETag Response Fingerprint of the resource version
If-None-Match Request Sends the last ETag; unchanged returns 304
Last-Modified / If-Modified-Since Both Time-based weak validation
Vary Response Which request headers key the cache (e.g. Accept-Encoding)
Retry-After Response When to retry after 429 or 503

Check them against the HTTP headers reference. Three practical notes: GET is cacheable by default, so it must never carry side effects — crawlers and prefetchers will trigger them; writes declare no-store; authenticated personalised responses need Cache-Control: private, or a shared cache may serve one user's data to another.

8. The Minimum Consensus on Auth

  • Force HTTPS and 301-redirect plain HTTP; certificate and TLS details live in the HTTPS certificate guide.
  • Do not invent a protocol: use OAuth 2.1 / OIDC or a mature session scheme, with token design in JWT security best practices; hash passwords with bcrypt, Argon2 or scrypt as covered in the password hashing guide.
  • Authorise on the server: a hidden button is not access control; rate-limit by identity rather than IP, or users behind one NAT block each other.

Ship Checklist

  1. URLs use plural nouns, lowercase, hyphens, no verbs, and at most two levels;
  2. Methods match semantics, safety and idempotency; every write endpoint answers "what happens on a retry", and non-idempotent writes carry Idempotency-Key (a reused key with a different body conflicts);
  3. Status codes are layered, and both 429 and 503 carry Retry-After;
  4. Errors are uniformly application/problem+json with a stable type, a business code, and field-level detail;
  5. Deep paging uses a cursor built on a unique, stable composite sort key;
  6. Compatible changes did not bump the version; breaking ones did and are staged;
  7. GET is safely cacheable, writes use no-store, personalised responses use private, HTTPS is enforced, and rate limits key on identity.

Frequently Asked Questions

Should I use PUT or PATCH?

PUT means full replacement, PATCH means partial update. PUT requires the client to submit the complete representation of the resource; missing fields are treated as deletions, and it is idempotent by nature — sending the same body a hundred times produces exactly the same result. PATCH submits only the fields being changed, which saves bandwidth, but it is not idempotent by default: an operation like { op: add, value: 1 } produces a different result on the second try. In practice: prefer PUT for setting a resource to a known state, and PATCH for changing a few specific fields. If PATCH also needs to be idempotent, only accept absolute values from the client rather than relative deltas. The deciding test is retry safety — if the endpoint can ever be retried automatically by a gateway or client, it must be idempotent.

Should the API version go in the URL or in a header?

There is no single right answer, but there are clear decision criteria. A URL prefix (/v1/orders) is the most discoverable: you can open it in a browser, it shows up directly in logs and monitoring, and it is the cheapest to debug — the cost is that the version leaks into the resource identifier. Header versioning (Accept: application/vnd.myapp.v1+json) keeps URLs clean and follows HTTP content negotiation, at the cost of hiding the version, breaking shareable links, and complicating gateway cache configuration. Pragmatic advice: use a URL prefix for public APIs aimed at external developers, where discoverability wins; use a header for internal services, where evolvability wins. The more important principle is avoid bumping the version at all. Backward-compatible changes — new optional fields, new enum values, new endpoints — never need a new version number; only breaking changes do. Treat v1 to v2 as an expensive product decision, not a number you increment casually.

Should pagination use offset or cursor, and why does deep paging get slower?

Use offset for shallow paging, and a cursor for deep paging or data that changes. The problem with ?offset=100000&limit=20 is that the database must scan and discard the first hundred thousand rows before returning anything, so the deeper the page, the slower it gets. Worse, if rows are inserted while the user pages through, offset causes duplicates or skipped records. A cursor relies on the sort key of the last row on the previous page — usually an auto-increment id or a timestamp — to fetch the next batch: ?cursor=eyJpZCI6MTAwMH0&limit=20. With a supporting index the lookup is direct, so cost is constant regardless of depth and it is immune to drift caused by inserts. The tradeoff is that a cursor cannot jump to an arbitrary page. The most common hybrid: offset for admin back offices that need page jumping and total counts, cursors for consumer feeds that only need load-more.

What format should error responses use? Isn't the HTTP status code enough?

It is not. The status code expresses only the category of the failure; the client also needs a stable, machine-readable reason. Returning a bare 400 with no detail forces the client to show the raw backend message to the user, and backend messages are rarely written for end users. RFC 7807 (problem+json) is the recommended envelope: it defines type, title, status, detail, and instance, and application/problem+json is natively supported by mainstream frameworks. Key practical points: 1. use the type field as a stable URI that identifies the error class, so clients branch on it rather than on prose; 2. add one custom extension field for a business error code (for example code: ORDER_ALREADY_PAID) to support localisation and monitoring aggregation; 3. always include field-level details for validation errors, otherwise form UX becomes unusable; 4. never echo stack traces, SQL, or internal hostnames in an error body.

← Back to Blog