API Design: REST, gRPC and GraphQL
Design resource-oriented REST APIs, know when gRPC or GraphQL fits better, and handle pagination, versioning and errors consistently.
Intermediate · about 4 hours · difficulty 2/5
Learn first: HTTP, Connections and Real-Time Protocols
The API is the contract between your system and its clients. In interviews, writing the key API endpoints early makes the rest of the design concrete.
REST done well
- Model resources as nouns: POST /orders, GET /orders/{id}, GET /users/{id}/orders.
- Use HTTP methods and status codes as intended (201 Created, 404, 409 Conflict, 429).
- Pagination: offset/limit is simple but slow and unstable on large, changing tables. Cursor (keyset) pagination (?after=<last_id>) is the scalable default for feeds and lists.
- Filtering and sorting with query parameters; partial responses with a fields parameter when payloads are big.
- Consistent errors: a machine-readable code, a human message and a request ID.
- Versioning: /v1/ in the path or a header. Prefer additive, backward-compatible changes so you rarely need v2.
gRPC
Binary Protocol Buffers over HTTP/2, generated clients, streaming in both directions. Excellent for internal service-to-service calls where you control both ends and care about latency. Less friendly for browsers and public APIs.
GraphQL
Clients ask for exactly the fields they need in one request. Great for apps with many screens over many services (a BFF layer). Costs: harder HTTP caching, risk of very expensive queries (add depth and cost limits), and N+1 resolver problems (use batching like DataLoader).
Picking one
- Public or partner API: REST with OpenAPI docs.
- Internal high-throughput calls: gRPC.
- Many client views with varied data needs: GraphQL at the edge, REST or gRPC behind it.
- Server push: WebSockets or SSE alongside any of these.
Pitfalls
- Verbs in URLs (/createOrder) and 200 OK with an error body.
- Offset pagination on a feed with millions of rows.
- Breaking changes without versioning.
You are ready to move on when you can write the five core endpoints for a ride-hailing app with request and response shapes, pagination and error codes.
Key concepts
- Resource-oriented REST
- Cursor vs offset pagination
- Error format and status codes
- API versioning
- gRPC and Protocol Buffers
- GraphQL trade-offs
- OpenAPI specs
Mini project
Write an OpenAPI spec for a mini food delivery API (restaurants, menus, carts, orders) with cursor pagination and a standard error schema. Implement two endpoints and the same order lookup as a gRPC service, then compare payload sizes.
Check yourself
Why does offset pagination produce duplicates or skipped items on a feed where new posts keep arriving, and how does cursor pagination avoid it?
Free resources
- Google API design guide (Google Cloud)
- Zalando RESTful API guidelines (Zalando)
- gRPC documentation (gRPC)
- Learn GraphQL (GraphQL Foundation)