API Design

Designing good APIs — REST resources and conventions, pagination, filtering, versioning, idempotency, errors, and when to choose gRPC or GraphQL instead.

Intermediate 3 min readLesson 11 of 20

An API is a contract that's hard to change once others depend on it. Good APIs are consistent, predictable, hard to misuse, and evolvable. This lesson focuses on design decisions; protocol details are in REST & GraphQL.

Choosing a style

StyleStrengthsWeaknessesTypical use
REST (HTTP + JSON)Universal, cacheable, simple, great toolingOver/under-fetching, many round tripsPublic APIs, web and mobile back ends
gRPC (HTTP/2 + Protobuf)Fast binary encoding, strict schemas, streaming, generated clientsNot browser-native, harder to debug by handInternal service-to-service calls
GraphQLClients ask for exactly the fields they need in one round trip; typed schemaCaching and rate limiting are harder; N+1 risks on the serverComplex UIs aggregating many resources
Webhooks / eventsPush notifications to other systemsDelivery and security to manageIntegrations ("payment succeeded")

REST conventions

Model resources (nouns) and use HTTP methods as verbs:

ActionRequestResponse
List ordersGET /v1/orders?status=paid&limit=20200 + list
Get oneGET /v1/orders/ord_123200 / 404
CreatePOST /v1/orders201 + Location: /v1/orders/ord_124
ReplacePUT /v1/orders/ord_123200 / 204
Update fieldsPATCH /v1/orders/ord_123200
DeleteDELETE /v1/orders/ord_123204
Sub-resourceGET /v1/customers/c_9/orders200
Action that isn't CRUDPOST /v1/orders/ord_123/cancel200

Guidelines: plural nouns, lowercase with hyphens, no verbs in paths (except explicit actions), consistent field naming (snake_case or camelCase, not both), ISO-8601 timestamps in UTC, and string IDs (opaque, prefixed like ord_ for readability).

Pagination

Offset pagination

GET /orders?offset=40&limit=20

  • Simple; supports "jump to page 7"
  • Slow for deep pages (the database scans and discards offset rows)
  • Items shift when rows are inserted or deleted (duplicates or gaps)
Cursor (keyset) pagination

GET /orders?limit=20&cursor=eyJpZCI6...

  • The cursor encodes the last item's sort key: WHERE (created_at, id) < (…) ORDER BY created_at DESC, id DESC LIMIT 20
  • Fast at any depth; stable under inserts
  • No random page access
  • The default for large or real-time data (feeds, logs)
JSON
{
  "data": [ { "id": "ord_123", "total": 4200 } ],
  "next_cursor": "eyJjcmVhdGVkX2F0IjoiMjAyNS0wMS0xNVQxMDowMDowMFoiLCJpZCI6Im9yZF8xMjMifQ",
  "has_more": true
}

Idempotency for safe retries

Networks fail: a client may not know whether its POST /payments succeeded. Retrying could charge twice. Idempotency keys fix it:

ClientAPIDBPOST /payments Idempotency-Key: 7f3a…store key + result (unique)201 (response lost in network ✗)retry with the same Idempotency-Keykey exists → return stored result201 (same payment, no double charge)

The server stores the key with the request's result (in the same transaction as the operation) and replays the stored response for repeats. Stripe's API popularised this.

Errors

Return the right status code and a consistent, machine-readable body:

JSON
{
  "error": {
    "type": "validation_error",
    "code": "amount_too_small",
    "message": "Amount must be at least 50 cents.",
    "param": "amount",
    "request_id": "req_8Hk2"
  }
}

The standard format RFC 9457 (Problem Details) is a good choice. Include a request ID for support and tracing; never leak stack traces.

Versioning and evolution

  • Additive changes are safe: new endpoints, new optional fields, new enum values (if clients tolerate unknown values).
  • Breaking changes — removing or renaming fields, changing types or semantics — need a new version: in the URL (/v2/), a header, or date-based versions (Stripe-style Stripe-Version: 2024-06-20).
  • Clients should ignore unknown fields (the robustness principle); servers should never repurpose a field.
  • Deprecate with notice, sunset headers and usage monitoring before removing anything.

Other essentials

  • Authentication and authorisation on every endpoint (OAuth 2.0 / API keys / JWT) — Authentication.
  • Rate limits with 429 and Retry-After — Rate limiting.
  • Filtering, sorting and field selection (?fields=id,total) to reduce payloads.
  • Long-running operations: return 202 Accepted with a status URL to poll, or a webhook on completion.
  • Documentation from a schema: OpenAPI for REST, .proto files for gRPC, SDL for GraphQL; generate clients and mock servers from it.
Key takeaways
  • Pick REST for public APIs, gRPC for internal high-performance calls, GraphQL for flexible client-driven data needs.
  • REST: resources as nouns, HTTP verbs, correct status codes, consistent naming.
  • Prefer cursor pagination for large or changing data.
  • Idempotency keys make retries of non-idempotent operations safe.
  • Consistent error bodies, additive evolution, explicit versioning for breaking changes.