Skip to content

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?

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.

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: Deprecation and Sunset headers, 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.
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 1
SELECT id, created_at, total_cents FROM orders
WHERE 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 orders
WHERE 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.

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 400 instead of ignoring them, which hides client typos for years.

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.1
Idempotency-Key: 7d3f9c1e-2a44-4b8e-9f11-3c2b7a1f0e55
Content-Type: application/json
{"amount_cents": 4200, "currency": "BRL"}

Server behaviour:

  1. Key absent → insert as processing with a hash of the body, then do the work.
  2. completed → replay the stored status and body.
  3. processing → 409 Conflict with Retry-After.
  4. Same key, different body hash → 422; the client reused a key, which is a bug worth surfacing.
  5. Expire after a window longer than any plausible retry (24 hours for payments).

Implementation detail and the concurrency argument are in Idempotency.

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..."
}
  • code is stable and machine-readable; detail is for humans and may change.
  • Include a request_id, and return the same value in X-Request-Id.
  • Never include stack traces, SQL, internal hostnames or exception class names.
  • 400 malformed input, 422 business rule violation, 409 state conflict.
HTTP/1.1 429 Too Many Requests
Retry-After: 12
RateLimit-Limit: 600
RateLimit-Remaining: 0
RateLimit-Reset: 12

Scope 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.

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_at and let the receiver decide.
  • Respond fast. Document that receivers should enqueue and return 200.
  • Allow secret rotation with two active secrets.
openapi.yaml (excerpt)
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.

  1. How do you add a required field without breaking existing clients?
  2. When is offset pagination acceptable?
  3. Why must an idempotency key store the response, not just the fact it was seen?
  4. How do you rate limit a webhook sender’s retries without dropping legitimate events?
  5. What is the difference between 409 and 422 on a retried request?
  • “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 Referer headers.