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
/orderItemsand/orderitemscan become two resources; - Hyphens for multi-word segments:
/order-items, no escaping needed; - No trailing slash. Some frameworks treat
/ordersand/orders/as separate routes.
Non-CRUD actions
Publish, cancel and batch-recalculate do not map onto CRUD. Three options, in priority order:
- Model the action as a resource:
POST /orders/1/cancellations— cancelling becomes creating a cancellation record, which is auditable; - Model it as a state field:
PATCH /orders/1with{ "status": "cancelled" }; - 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-Afteris 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:
typeis the stable contract. Clients branch on it, never ondetailprose — prose changes, the URI should not;codeis a deliberate extension for localisation and log aggregation, where the same code groups directly;errorscarries field-level detail. Form endpoints are unusable without it;- 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
- URLs use plural nouns, lowercase, hyphens, no verbs, and at most two levels;
- 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); - Status codes are layered, and both 429 and 503 carry
Retry-After; - Errors are uniformly
application/problem+jsonwith a stabletype, a businesscode, and field-level detail; - Deep paging uses a cursor built on a unique, stable composite sort key;
- Compatible changes did not bump the version; breaking ones did and are staged;
- GET is safely cacheable, writes use
no-store, personalised responses useprivate, HTTPS is enforced, and rate limits key on identity.