Skip to Content
Mengty Learns
Architecture

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.

referenceintermediateTested with rfc_9110 2022-06 (spec), rfc_9457 2023-07 (spec), openapi 3.2.1 (spec)Updated Nov 27, 2026

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.

OpenAPI anchors both request validation and RFC 9457 error shapes at the API boundary.

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}/cancellations with POST).

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.

MethodSafeIdempotentTypical useCommon status codes
GETYesYesRead resource or collection200 OK, 304 Not Modified, 404 Not Found
POSTNoNoCreate resource or trigger action201 Created (Location header), 202 Accepted, 400, 409, 422
PUTNoYesFull replacement of a known URI200 OK, 204 No Content, 409 Conflict
PATCHNoNo*Partial update (merge-patch+json)200 OK, 204 No Content, 422 Unprocessable Content
DELETENoYesRemove resource204 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:

  1. Store (idempotency_key, request_hash, status_code, response_body) in Redis or Postgres with a TTL (e.g., 24 hours).
  2. If the same key arrives with the same payload hash, replay the stored response without re-running the mutation.
  3. If the same key arrives with a different payload hash, return 422 or 409 so bugs surface immediately.

4. Pagination and filtering

StrategyQuery shapeProsCons
Offset?limit=20&offset=40Easy "jump to page 5" UISlow O(offset + limit) DB scans; rows shift on concurrent inserts (duplicates/skips)
Cursor (keyset)?limit=20&cursor=eyJpZCI6MTAwfQConstant O(log N) index seek; stable under writesCannot 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

StyleBest fitTrade-off
REST (HTTP + JSON)Public APIs, CRUD services, browser/mobile backendsOver-fetching/under-fetching on deeply nested graphs
gRPC (HTTP/2 + Protobuf)High-throughput internal microservices, streamingNeeds proxy (gRPC-Web/Envoy) for browsers; binary payloads harder to inspect with curl
GraphQLComplex UIs aggregating many entities with varied client needsN+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.json with 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 OFFSET queries at 1M+ rows.

Gotchas

  • Leaking stack traces in problem+json: Never put SQL errors, file paths, or internal hostnames into detail in production—log them server-side with a trace_id extension field instead.
  • Returning 200 OK with { "ok": false }: Proxies, CDNs, and client SDKs rely on HTTP status codes (4xx/5xx) for retries and error handling.
  • Unbounded limit parameter: Always clamp limit (e.g., default 20, max 100) so ?limit=1000000 cannot OOM your API or database.

Production checklist

  • Every 4xx/5xx response uses application/problem+json (RFC 9457) with no internal stack traces.
  • List endpoints enforce a maximum limit and use cursor pagination for large tables.
  • Money, order, and webhook-driven POST endpoints require and deduplicate Idempotency-Key.
  • OpenAPI spec is checked in CI for breaking changes before merge.
  • 429 responses include Retry-After and 5xx responses 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