API Design
An API is a contract with clients you do not control and cannot redeploy. Most API design questions are really about change: how do you add, remove, rename and retry without breaking strangers?
The 60-second answer
Section titled “The 60-second answer”Design around resources with predictable URLs and HTTP semantics. Version explicitly and only break on a new major version. Paginate everything that can grow, with cursors rather than offsets for large or changing data. Accept an idempotency key on unsafe operations so clients can retry safely. Return a single machine-readable error shape with a stable code. Rate limit with standard headers. Sign webhooks and make them idempotent, because delivery is at-least-once. Publish an OpenAPI document and treat it as the contract.
Versioning
Section titled “Versioning”| Strategy | Example | Trade-off |
|---|---|---|
| Path | /v1/orders |
Obvious, easy to route, cache and log. Most common |
| Header | Accept: application/vnd.acme.v1+json |
“Pure” REST; invisible in logs, harder to cache |
| Query | ?version=1 |
Easy to forget; pollutes cache keys |
| Additive only | Add fields, never remove | Works until it does not |
- Version the major number only. Additive changes — new optional fields, new endpoints, new enum members clients tolerate — need no bump.
- Never change a field’s meaning, tighten validation, or change a default. Those are breaking even though the JSON still parses.
- Deprecate with notice:
DeprecationandSunsetheaders, a changelog, and per-client usage metrics so you know who still calls the old endpoint. - Keep old versions for a stated window, then delete them.
Pagination
Section titled “Pagination”| Style | Request | Strength | Weakness |
|---|---|---|---|
| Offset/limit | ?offset=200&limit=50 |
Simple, random access | Cost grows with offset; rows shift |
| Cursor/keyset | ?limit=50&after=<opaque> |
Stable under inserts, constant cost | No random access |
| Time-based | ?before=<timestamp> |
Natural for feeds | Ties collide |
-- page 1SELECT id, created_at, total_cents FROM ordersWHERE customer_id = $1 ORDER BY created_at DESC, id DESC LIMIT 50;
-- next page: last row was (2026-03-01T10:00:00Z, 8891)SELECT id, created_at, total_cents FROM ordersWHERE customer_id = $1 AND (created_at, id) < ($2, $3)ORDER BY created_at DESC, id DESC LIMIT 50;The composite comparison (created_at, id) < (...) is what makes the cursor total when timestamps
repeat — always include id in the sort key.
{ "data": [ { "id": 8891, "total_cents": 4200 } ], "page": { "next_cursor": "eyJjIjoiMjAyNi0wMy0wMVQxMDowMDowMFoiLCJpIjo4ODkxfQ", "has_more": true }}Avoid returning total counts on large filtered sets: COUNT(*) is a full scan. If you must, cache it
and label it approximate.
Filtering, sorting, sparse fields
Section titled “Filtering, sorting, sparse fields”GET /v1/orders?status=paid&created_after=2026-01-01&sort=-created_at&fields=id,total_cents- Whitelist filterable and sortable fields. A raw
sort=value passed to SQL is injection and an index-misuse vector. - Encode the sort direction in the cursor, or page 2 can use a different ordering from page 1.
- Reject unknown parameters with
400instead of ignoring them, which hides client typos for years.
Idempotency keys
Section titled “Idempotency keys”Any POST that creates something or moves money must be retryable. The client generates a key and
repeats it on retry.
POST /v1/payments HTTP/1.1Idempotency-Key: 7d3f9c1e-2a44-4b8e-9f11-3c2b7a1f0e55Content-Type: application/json
{"amount_cents": 4200, "currency": "BRL"}Server behaviour:
- Key absent → insert as
processingwith a hash of the body, then do the work. completed→ replay the stored status and body.processing→409 ConflictwithRetry-After.- Same key, different body hash →
422; the client reused a key, which is a bug worth surfacing. - Expire after a window longer than any plausible retry (24 hours for payments).
Implementation detail and the concurrency argument are in Idempotency.
Error format
Section titled “Error format”One shape for every error, including 500s. RFC 9457 (Problem Details, obsoleting RFC 7807):
{ "type": "https://api.example.com/problems/insufficient-funds", "title": "Insufficient funds", "status": 422, "detail": "Balance 1500 is below the requested 4200.", "code": "payment.insufficient_funds", "errors": [{ "field": "amount_cents", "message": "must be <= available balance" }], "request_id": "req_01HZX..."}codeis stable and machine-readable;detailis for humans and may change.- Include a
request_id, and return the same value inX-Request-Id. - Never include stack traces, SQL, internal hostnames or exception class names.
400malformed input,422business rule violation,409state conflict.
Rate limiting
Section titled “Rate limiting”HTTP/1.1 429 Too Many RequestsRetry-After: 12RateLimit-Limit: 600RateLimit-Remaining: 0RateLimit-Reset: 12Scope limits to the identity that matters: API key for server clients, user id for authenticated
requests, IP only as a coarse backstop (NAT and mobile carriers make IPs unreliable). Different
endpoints deserve different budgets. Return 429, never 503, for quota exhaustion — 503 means
the service is down and triggers different client behaviour. See
Rate Limiting.
Webhooks
Section titled “Webhooks”A webhook is a POST to a subscriber URL. You are the client now, and their server will be down,
slow and duplicated.
- Sign every request: HMAC-SHA256 over
timestamp + "." + raw_body. Sign the raw bytes, before JSON parsing, or canonicalisation differences break verification. - Include a timestamp and reject old ones (five minutes) to stop replay.
- Stable event id so receivers deduplicate. Delivery is at-least-once; assume everything arrives twice.
- Retry with exponential backoff and jitter for hours to a day, then a dead-letter queue visible in the dashboard.
- Order is not guaranteed. Send a sequence number or
occurred_atand let the receiver decide. - Respond fast. Document that receivers should enqueue and return
200. - Allow secret rotation with two active secrets.
OpenAPI
Section titled “OpenAPI”paths: /v1/orders: get: parameters: - name: limit in: query schema: { type: integer, minimum: 1, maximum: 100, default: 20 }Treat the document as the contract: generate stubs and clients from it, validate requests in CI, and diff it on every pull request so breaking changes fail the build. Keep examples inline — they are what people copy.
Follow-up questions
Section titled “Follow-up questions”- How do you add a required field without breaking existing clients?
- When is offset pagination acceptable?
- Why must an idempotency key store the response, not just the fact it was seen?
- How do you rate limit a webhook sender’s retries without dropping legitimate events?
- What is the difference between
409and422on a retried request?
Common traps
Section titled “Common traps”- “We will version when we need to.” Then the first breaking change is an outage.
- “Offset pagination is fine, the table is small.” It will not be; cursors remove a migration.
- “Idempotent means safe to call twice.” Only with a key that is provided and stored.
- “Webhooks are reliable because we retry.” Retries create duplicates; receiver idempotency is mandatory.
- “200 with
{"error": ...}is friendlier.” It breaks clients, caches, monitors and retry libraries. - “The API key is in the URL, so it works everywhere.” URLs leak into logs, proxies and
Refererheaders.