HTTP API Design Reference
Practical REST conventions, RFC 9110 methods and status codes, idempotency keys, cursor pagination, RFC 9457 problem+json errors, OpenAPI, and REST vs gRPC vs GraphQL.
TL;DR
Design HTTP APIs around nouns for resources, RFC 9110 method/status semantics, cursor pagination, and Idempotency-Key headers on POST mutations. Return consistent application/problem+json (RFC 9457) errors, publish an OpenAPI contract, and only reach for gRPC or GraphQL when REST's request/response model genuinely hurts.
Why it exists
Inconsistent APIs force every client to guess URL shapes, parse ad-hoc error JSON ({ error }, { message }, { errors: [...] }), and break silently when fields change or retries fire twice. Standardizing on HTTP semantics and a machine-readable contract removes guesswork for both frontend callers and backend services.
Mental model
Treat HTTP as the protocol, not a tunnel for RPC verbs. Resources are nouns (/orders, /orders/{id}), HTTP methods express intent, status codes tell intermediaries and clients how to react (cache, retry, or fix input), and OpenAPI is the shared source of truth between producer and consumer.
Core conventions
1. Resource naming
- Use plural nouns and kebab-case or snake_case consistently:
/orders,/orders/{orderId}/items. - Keep nesting shallow (at most 2 levels:
/users/{id}/tokens; beyond that, promote/tokens?user_id=...). - Avoid verbs in paths (
/getOrder,/createUser). For non-CRUD state transitions, use a sub-resource noun or action resource (/orders/{id}/cancellationswithPOST).
2. HTTP methods and status codes (RFC 9110)
Per RFC 9110 §9.2, safe methods do not alter server state; idempotent methods leave the server in the same state whether called once or N times.
| Method | Safe | Idempotent | Typical use | Common status codes |
|---|---|---|---|---|
GET | Yes | Yes | Read resource or collection | 200 OK, 304 Not Modified, 404 Not Found |
POST | No | No | Create resource or trigger action | 201 Created (Location header), 202 Accepted, 400, 409, 422 |
PUT | No | Yes | Full replacement of a known URI | 200 OK, 204 No Content, 409 Conflict |
PATCH | No | No* | Partial update (merge-patch+json) | 200 OK, 204 No Content, 422 Unprocessable Content |
DELETE | No | Yes | Remove resource | 204 No Content, 404 Not Found |
*PATCH can be made idempotent in specific designs (e.g., setting status = "cancelled"), but is not guaranteed idempotent by RFC 9110.
Use 401 Unauthorized when credentials are missing/invalid, 403 Forbidden when the authenticated caller lacks permission, 429 Too Many Requests (with Retry-After) for rate limits, and 503 Service Unavailable for temporary overload.
3. Idempotency keys
Mobile networks and webhooks retry timed-out POST requests. Require an Idempotency-Key: <uuid> header on payment, order, or side-effecting POST endpoints:
- Store
(idempotency_key, request_hash, status_code, response_body)in Redis or Postgres with a TTL (e.g., 24 hours). - If the same key arrives with the same payload hash, replay the stored response without re-running the mutation.
- If the same key arrives with a different payload hash, return
422or409so bugs surface immediately.
4. Pagination and filtering
| Strategy | Query shape | Pros | Cons |
|---|---|---|---|
| Offset | ?limit=20&offset=40 | Easy "jump to page 5" UI | Slow O(offset + limit) DB scans; rows shift on concurrent inserts (duplicates/skips) |
| Cursor (keyset) | ?limit=20&cursor=eyJpZCI6MTAwfQ | Constant O(log N) index seek; stable under writes | Cannot jump to arbitrary page numbers |
Default to cursor pagination for feeds, logs, and growing tables. For filtering and sorting, accept explicit query parameters (?status=paid&sort=-created_at) and validate sort keys against a strict server-side allowlist.
5. Consistent error format (RFC 9457)
Return Content-Type: application/problem+json with a stable schema so clients never scrape human error strings:
{
"type": "https://api.example.com/problems/insufficient-balance",
"title": "Insufficient account balance",
"status": 422,
"detail": "Account acct_42 has $12.00 available, which is less than the $25.00 transfer.",
"instance": "/transfers/tr_981",
"available_cents": 1200,
"required_cents": 2500
}6. Versioning and OpenAPI
- Prefer additive changes (optional fields, new endpoints) before bumping a version.
- When breaking changes are unavoidable, URI prefixing (
/v1/orders) is the simplest to route, cache, and debug; header/media-type versioning (Accept: application/vnd.api.v2+json) keeps URLs clean at the cost of harder browser/CDN debugging. - OpenAPI (v3.2.1) acts as the machine-readable contract: validate requests at the gateway, generate TypeScript clients, and catch breaking diffs in CI.
7. REST vs gRPC vs GraphQL
| Style | Best fit | Trade-off |
|---|---|---|
| REST (HTTP + JSON) | Public APIs, CRUD services, browser/mobile backends | Over-fetching/under-fetching on deeply nested graphs |
| gRPC (HTTP/2 + Protobuf) | High-throughput internal microservices, streaming | Needs proxy (gRPC-Web/Envoy) for browsers; binary payloads harder to inspect with curl |
| GraphQL | Complex UIs aggregating many entities with varied client needs | N+1 resolver traps, caching complexity, query-depth/cost DoS surface |
When you DON'T need this
- Internal single-app forms or tiny prototypes: If one Next.js frontend talks to two private route handlers you own, skip API versioning, hypermedia, and GraphQL—just use typed JSON endpoints with Zod validation and RFC 9457 errors.
- Static sites: This site exports static files and
public/cards.jsonwith zero runtime API. - Cost / complexity trade-off: Adding OpenAPI codegen, idempotency stores, and cursor tokens takes upfront engineering time. In exchange, you avoid silent breaking changes, duplicate financial writes, and slow
OFFSETqueries at 1M+ rows.
Gotchas
- Leaking stack traces in
problem+json: Never put SQL errors, file paths, or internal hostnames intodetailin production—log them server-side with atrace_idextension field instead. - Returning
200 OKwith{ "ok": false }: Proxies, CDNs, and client SDKs rely on HTTP status codes (4xx/5xx) for retries and error handling. - Unbounded
limitparameter: Always clamplimit(e.g., default20, max100) so?limit=1000000cannot OOM your API or database.
Production checklist
- Every
4xx/5xxresponse usesapplication/problem+json(RFC 9457) with no internal stack traces. - List endpoints enforce a maximum
limitand use cursor pagination for large tables. - Money, order, and webhook-driven
POSTendpoints require and deduplicateIdempotency-Key. - OpenAPI spec is checked in CI for breaking changes before merge.
-
429responses includeRetry-Afterand5xxresponses are safe for clients to retry only on idempotent methods or with an idempotency key.
Check yourself
Check Yourself
1. A client times out after sending POST /payments and retries the exact same request. How do you prevent a double charge?
2. Why does RFC 9457 recommend application/problem+json over ad-hoc { error: '...' } objects?
3. Which pagination approach avoids skipped or duplicated items when new rows are inserted between page fetches?
Sources
Related Notes
Queues & Asynchronous Work
Decouple slow work from HTTP requests with queues vs pub/sub, at-least-once delivery, idempotency keys, exponential backoff retries, and dead-letter queues.
The C4 Model: Context, Container, Component, Code
Visualize software architecture at four zoom levels—System Context, Containers, Components, and Code—applied to Mengty Learns itself.