An API is a contract: once other teams, apps or customers depend on it, every decision becomes expensive to change. Good API design makes the common case obvious, failures explicit and evolution possible without breaking clients. This lesson covers REST conventions (naming, versioning, pagination, errors, idempotency, rate limits), then GraphQL and gRPC, when to choose each, and webhooks for pushing events to other systems.
Think of it like
A restaurant menu
A menu (the API) hides the kitchen (the implementation). REST is a classic à la carte menu: a fixed set of dishes, each ordered separately. GraphQL is a build-your-own bowl: one counter, you list exactly the ingredients you want. gRPC is the kitchen's internal ticket system: terse, fast and only readable by staff who know the codes. And once customers have favorite dishes, you can add new ones, but quietly changing a recipe makes people angry. That is versioning.
What makes an API good
- Consistent: the same naming, pagination, error format and auth everywhere. Learning one endpoint teaches you all of them.
- Predictable: correct HTTP methods and status codes, so generic clients, caches and retries behave correctly (see HTTP, HTTPS & TLS).
- Hard to misuse: safe defaults, bounded page sizes, idempotent retries, clear validation errors.
- Evolvable: new fields and endpoints can be added without breaking existing clients.
- Documented by a schema: OpenAPI for REST, SDL for GraphQL,
.protofiles for gRPC. Schemas enable code generation and contract tests.
REST principles
- Resources
- Everything is a noun with a URL:
/users/7,/orders/9001. Clients manipulate representations of resources (usually JSON). - Uniform interface
- A small fixed set of verbs (
GET,POST,PUT,PATCH,DELETE) with standard semantics, instead of custom operations per endpoint. - Stateless
- Each request carries everything needed to process it (including credentials). Servers keep no per-client session, which makes horizontal scaling easy. See Scalability.
- Cacheable
- Responses declare whether and how long they can be cached, so CDNs and browsers can absorb reads.
- Layered system
- Clients cannot tell whether they talk to the origin or a proxy, gateway or CDN in between.
- HATEOAS
- Responses include links to related actions. Part of the original definition, rarely implemented fully in practice.
Resource naming
| Prefer | Avoid | Why |
|---|---|---|
GET /users/7/orders | GET /getOrdersForUser?id=7 | Nouns plus HTTP verbs, not verbs in the path |
POST /orders | POST /order/create | Plural collections; POST already means create |
GET /orders/9001 | GET /orders?id=9001 | A single resource has its own URL |
/payment-methods | /paymentMethods, /payment_methods | Lowercase kebab-case paths are the most common convention |
GET /orders?customer=7 | /customers/7/orders/9001/items/3/notes | Keep nesting shallow; deep paths couple clients to hierarchy |
POST /orders/9001/cancel | PATCH /orders/9001 {status: "canceled"} | Model business actions with side effects as explicit sub-resources |
GET /v1/orders?status=open&limit=20&cursor=... list (paginated, filtered)
POST /v1/orders create -> 201 + Location
GET /v1/orders/{id} read -> 200 / 404
PATCH /v1/orders/{id} partial edit -> 200 / 409 / 422
DELETE /v1/orders/{id} remove -> 204
POST /v1/orders/{id}/cancel action -> 202
GET /v1/customers/{id}/orders sub-collectionVersioning
Additive changes are safe: new endpoints, new optional fields, new enum values that clients are told to tolerate. Breaking changes need a new version: removing or renaming a field, changing a type, making an optional field required, or changing what a status code means.
| Strategy | Example | Pros | Cons |
|---|---|---|---|
| URL path | /v1/orders, /v2/orders | Obvious, easy to route, cache and test in a browser | Coarse: one change bumps the whole API |
| Header / media type | Accept: application/vnd.shop.v2+json | Clean URLs; per-resource versions | Invisible in logs and links; harder to test |
| Query parameter | /orders?version=2 | Simple to add | Easy to forget; pollutes cache keys |
| Date-based | Stripe-Version: 2024-06-20 | Each account pins a version; small, frequent changes | Server must maintain transforms between many versions |
Pagination
Never return an unbounded list. The two main approaches differ in how they remember "where you were".
Offset / limit
GET /orders?offset=40&limit=20- Simple; supports "jump to page 37" and total counts
OFFSET 1000000still scans and discards a million rows: O(offset)- Rows inserted or deleted between requests cause duplicates or skipped items
- Fine for small admin tables and search results with page numbers
Cursor (keyset)
GET /orders?limit=20&cursor=eyJ0Ijo...- The cursor encodes the last row's sort key, e.g.
(created_at, id) - Index seek straight to the position: constant cost at any depth
- Stable under concurrent inserts: no duplicates or gaps
- No random access to page N; sort order is fixed by the cursor's key
-- Offset: the database walks and discards 100,000 rows to return 20
SELECT id, created_at, total FROM orders
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 100000;
-- Keyset: seek on the index (created_at, id) and read 20 rows
SELECT id, created_at, total FROM orders
WHERE (created_at, id) < ('2026-10-01 12:00:00', 88123)
ORDER BY created_at DESC, id DESC
LIMIT 20;
CREATE INDEX orders_created_id ON orders (created_at DESC, id DESC);{
"data": [
{ "id": 88122, "createdAt": "2026-10-01T11:58:02Z", "total": 4599 },
{ "id": 88119, "createdAt": "2026-10-01T11:57:40Z", "total": 1250 }
],
"nextCursor": "WyIyMDI2LTEwLTAxVDExOjU3OjQwWiIsODgxMTld",
"hasMore": true
}Filtering, sorting and field selection
- Filters as query parameters:
?status=open&created_after=2026-10-01. Document which fields are filterable and back each with an index. - Sorting with an allowlist:
?sort=-created_at,total(a leading minus means descending). Reject unknown fields rather than passing them to SQL. - Sparse fieldsets:
?fields=id,total,statusto trim payloads for mobile clients. - Cap
limiton the server (for example 100) no matter what the client asks for.
Errors
Use the right status code and a consistent machine-readable body. RFC 9457 "Problem Details" (application/problem+json) is a widely adopted standard shape. Include a stable error type or code that clients can branch on, a human message, and a request ID for support.
{
"type": "https://api.shop.example.com/errors/validation",
"title": "Your request has invalid fields.",
"status": 422,
"detail": "2 fields failed validation.",
"instance": "/v1/orders",
"requestId": "req_01J9ZQ4M3T",
"errors": [
{ "field": "quantity", "code": "min", "message": "must be at least 1" },
{ "field": "shippingAddress.postalCode", "code": "format", "message": "invalid postal code" }
]
}Idempotency keys and rate limits
Networks fail in the worst possible place: after the server committed the work but before the client got the response. The client cannot tell whether to retry. An idempotency key (a client-generated UUID sent in a header) lets the server recognize a retry and replay the original result instead of charging the card twice. The diagram also shows how a gateway enforces rate limits before requests reach the service.
HTTP/1.1 429 Too Many Requests
Retry-After: 30
X-RateLimit-Limit: 100 <- requests allowed per window
X-RateLimit-Remaining: 0 <- left in the current window
X-RateLimit-Reset: 1761825600 <- when the window resets (Unix time)GraphQL
GraphQL exposes a single endpoint (usually POST /graphql) and a typed schema. Clients send a query describing exactly the fields they need, possibly spanning several resources, and get back JSON in the same shape. This solves REST's over-fetching (getting fields you don't need) and under-fetching (needing several round trips for one screen).
type Query {
user(id: ID!): User
feed(first: Int = 20, after: String): PostConnection!
}
type Mutation {
likePost(postId: ID!): Post!
}
type User {
id: ID!
name: String!
avatarUrl: String
}
type Post {
id: ID!
title: String!
author: User!
likeCount: Int!
}
type PostConnection {
edges: [Post!]!
endCursor: String
hasNextPage: Boolean!
}query HomeScreen {
user(id: "7") { name avatarUrl }
feed(first: 10) {
edges { id title likeCount author { name } }
endCursor
hasNextPage
}
}On the server, each field has a resolver function. The engine walks the query tree calling resolvers, which makes GraphQL flexible but introduces a classic trap: the N+1 problem. Resolving feed runs 1 query for 10 posts, then author runs once per post: 10 more queries. With nested lists this multiplies quickly.
import DataLoader from "dataloader";
// Create loaders per request so cached values never leak between users.
export function createLoaders() {
return {
user: new DataLoader<string, User>(async (ids) => {
// All author IDs requested in the same tick arrive here as ONE batch.
const rows = await db.query<User>("SELECT * FROM users WHERE id = ANY($1)", [ids]);
const byId = new Map(rows.map((u) => [u.id, u]));
// DataLoader requires results in the same order as the keys.
return ids.map((id) => byId.get(id) ?? new Error("user not found: " + id));
}),
};
}
export const resolvers = {
Query: {
feed: (_: unknown, args: { first: number }) =>
db.query<Post>("SELECT * FROM posts ORDER BY created_at DESC LIMIT $1", [args.first]),
},
Post: {
// 10 posts -> 10 load() calls -> 1 SQL query instead of 10
author: (post: Post, _: unknown, ctx: { loaders: ReturnType<typeof createLoaders> }) =>
ctx.loaders.user.load(post.authorId),
},
};- Caching is harder: every query is a
POSTto one URL, so HTTP and CDN caching do not work out of the box. Persisted queries (a hash sent withGET) and client-side normalized caches help. - Cost control: a malicious or careless client can request deeply nested data. Enforce depth and complexity limits and timeouts.
- Errors: responses are usually
200with anerrorsarray, so monitoring must inspect bodies, not just status codes.
gRPC
gRPC is a high-performance RPC framework from Google. You define services and messages in Protocol Buffers, generate strongly typed clients and servers in many languages, and calls travel as compact binary messages over HTTP/2. It dominates internal service-to-service traffic where both sides are under your control.
syntax = "proto3";
package orders.v1;
service OrderService {
rpc GetOrder(GetOrderRequest) returns (Order); // unary
rpc WatchOrder(GetOrderRequest) returns (stream OrderEvent); // server streaming
rpc UploadItems(stream LineItem) returns (UploadSummary); // client streaming
rpc SupportChat(stream ChatMessage) returns (stream ChatMessage); // bidirectional
}
message GetOrderRequest { string order_id = 1; }
message Order {
string id = 1;
string customer_id = 2;
int64 total_cents = 3;
Status status = 4;
enum Status {
STATUS_UNSPECIFIED = 0;
PENDING = 1;
PAID = 2;
SHIPPED = 3;
}
}
message OrderEvent { string order_id = 1; Order.Status status = 2; int64 at_unix_ms = 3; }
message LineItem { string sku = 1; int32 quantity = 2; }
message UploadSummary { int32 accepted = 1; int32 rejected = 2; }
message ChatMessage { string from = 1; string text = 2; }| Mode | Shape | Example |
|---|---|---|
| Unary | One request, one response | GetOrder: a normal function call |
| Server streaming | One request, a stream of responses | Watch order status, download a large result in chunks |
| Client streaming | A stream of requests, one response | Upload telemetry or line items, then get a summary |
| Bidirectional streaming | Both sides stream independently | Chat, live collaboration, multiplayer state |
REST vs GraphQL vs gRPC
| REST | GraphQL | gRPC | |
|---|---|---|---|
| Transport | HTTP/1.1, 2 or 3 | Usually HTTP POST to one endpoint | HTTP/2 |
| Payload | JSON (text) | JSON (text) | Protobuf (binary, compact) |
| Contract | OpenAPI (optional) | Schema (required, introspectable) | .proto (required, code-generated) |
| Fetching | Fixed shape per endpoint | Client picks exact fields | Fixed shape per method |
| HTTP caching | Excellent (GET + CDN) | Hard without persisted queries | None built in |
| Streaming | Via SSE or WebSocket | Subscriptions (usually WebSocket) | Native, four modes |
| Browser support | Native | Native | Needs gRPC-Web or a proxy |
| Best for | Public APIs, CRUD, cacheable reads | Many client types with varied data needs | Internal microservices, low latency, polyglot |
Webhooks
APIs answer when asked; webhooks call you when something happens. The provider sends an HTTP POST to a URL the consumer registered (for example payment.succeeded). They are how Stripe, GitHub and Shopify notify integrations without polling.
- 1
Register
The consumer registers an HTTPS endpoint and the event types it wants, and receives a signing secret.
- 2
Deliver
On each event the provider POSTs a JSON payload with an event ID, type, timestamp and an HMAC signature header.
- 3
Verify
The consumer recomputes the HMAC over the raw body and timestamp with the shared secret, compares in constant time, and rejects stale timestamps to stop replays.
- 4
Acknowledge fast
Return
2xxwithin a few seconds and do the real work asynchronously (enqueue it). Slow handlers cause timeouts and redundant retries. - 5
Retry and deduplicate
Providers retry failed deliveries with exponential backoff for hours or days, so delivery is at least once and may be out of order. Deduplicate by event ID and re-fetch current state when ordering matters.
Implementation
Fetch one extra row to know whether another page exists, and hand back an opaque cursor built from the last row's sort key.
import base64
import json
import sqlite3
def encode_cursor(created_at: str, row_id: int) -> str:
return base64.urlsafe_b64encode(json.dumps([created_at, row_id]).encode()).decode()
def decode_cursor(cursor: str) -> tuple[str, int]:
created_at, row_id = json.loads(base64.urlsafe_b64decode(cursor))
return created_at, row_id
def list_orders(db: sqlite3.Connection, limit: int = 20, cursor: str | None = None) -> dict:
limit = max(1, min(limit, 100)) # never trust the client's page size
if cursor:
created_at, row_id = decode_cursor(cursor)
rows = db.execute(
"""SELECT id, created_at, total FROM orders
WHERE (created_at, id) < (?, ?)
ORDER BY created_at DESC, id DESC
LIMIT ?""",
(created_at, row_id, limit + 1),
).fetchall()
else:
rows = db.execute(
"SELECT id, created_at, total FROM orders ORDER BY created_at DESC, id DESC LIMIT ?",
(limit + 1,),
).fetchall()
has_more = len(rows) > limit # the extra row tells us another page exists
rows = rows[:limit]
next_cursor = encode_cursor(rows[-1][1], rows[-1][0]) if has_more else None
return {
"data": [{"id": r[0], "createdAt": r[1], "total": r[2]} for r in rows],
"nextCursor": next_cursor,
"hasMore": has_more,
}Key takeaways
- Design REST around plural nouns and standard methods; model side-effecting business actions as explicit sub-resources.
- Evolve additively within a major version; breaking changes need a new version and a loud deprecation period.
- Prefer cursor (keyset) pagination for large or live data: constant cost at any depth and stable under inserts.
- Use consistent machine-readable errors, idempotency keys for retryable POSTs, and rate-limit headers on every response.
- GraphQL fixes over- and under-fetching but needs DataLoader for N+1, complexity limits and extra caching work.
- gRPC gives typed, binary, streaming RPC over HTTP/2: ideal between internal services, awkward in browsers.
Common pitfalls
- Offset pagination on huge or fast-changing tables, causing slow deep pages and duplicated or skipped items.
- Returning
200with an error payload, or inconsistent error shapes across endpoints. - Breaking clients by renaming fields or changing types in place instead of versioning.
- Retrying POSTs without idempotency keys and creating duplicate orders or charges.
- Trusting webhook payloads without verifying signatures and timestamps, or doing slow work before acknowledging them.
Interview tips
- Write the API out explicitly in the interview: method, path, key fields, status codes and pagination. It anchors the rest of the design.
- Mention idempotency for any write that moves money or creates resources, and explain how the key is stored and replayed.
- When asked REST vs GraphQL vs gRPC, answer by audience: public clients, many varied frontends, or internal services.
Real-world applications
- Public developer platforms (Stripe, GitHub, Twilio) with versioned REST and webhooks.
- Mobile backends-for-frontends using GraphQL to minimize round trips.
- Microservice meshes using gRPC with deadlines and streaming.
- Infinite-scroll feeds and activity logs using cursor pagination.
Test yourself
Why does OFFSET 1000000 LIMIT 20 get slow while keyset pagination stays fast?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.