API Design
Designing good APIs — REST resources and conventions, pagination, filtering, versioning, idempotency, errors, and when to choose gRPC or GraphQL instead.
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
| Style | Strengths | Weaknesses | Typical use |
|---|---|---|---|
| REST (HTTP + JSON) | Universal, cacheable, simple, great tooling | Over/under-fetching, many round trips | Public APIs, web and mobile back ends |
| gRPC (HTTP/2 + Protobuf) | Fast binary encoding, strict schemas, streaming, generated clients | Not browser-native, harder to debug by hand | Internal service-to-service calls |
| GraphQL | Clients ask for exactly the fields they need in one round trip; typed schema | Caching and rate limiting are harder; N+1 risks on the server | Complex UIs aggregating many resources |
| Webhooks / events | Push notifications to other systems | Delivery and security to manage | Integrations ("payment succeeded") |
REST conventions
Model resources (nouns) and use HTTP methods as verbs:
| Action | Request | Response |
|---|---|---|
| List orders | GET /v1/orders?status=paid&limit=20 | 200 + list |
| Get one | GET /v1/orders/ord_123 | 200 / 404 |
| Create | POST /v1/orders | 201 + Location: /v1/orders/ord_124 |
| Replace | PUT /v1/orders/ord_123 | 200 / 204 |
| Update fields | PATCH /v1/orders/ord_123 | 200 |
| Delete | DELETE /v1/orders/ord_123 | 204 |
| Sub-resource | GET /v1/customers/c_9/orders | 200 |
| Action that isn't CRUD | POST /v1/orders/ord_123/cancel | 200 |
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
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)
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)
{
"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:
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:
{
"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-styleStripe-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
429andRetry-After— Rate limiting. - Filtering, sorting and field selection (
?fields=id,total) to reduce payloads. - Long-running operations: return
202 Acceptedwith a status URL to poll, or a webhook on completion. - Documentation from a schema: OpenAPI for REST,
.protofiles for gRPC, SDL for GraphQL; generate clients and mock servers from it.
- 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.