API Design: REST, GraphQL and gRPC
Every system design interview has an API section. It usually comes right after the core entities and takes five minutes, and many candidates rush through it by listing a few endpoints with vague names. That's a missed opportunity. The API is the contract between your system and everyone who uses it, and the way you write it shows whether you understand HTTP, how clients actually behave, and where your system's security boundary is.
A good API section also does real work for the rest of the interview. It pins down exactly what the system has to support, it exposes questions you need to answer (is this read paginated? who is allowed to call this?), and it gives you and your interviewer a shared vocabulary for the high-level design.
We'll build this up in layers:
- REST, the default for public and product APIs: resources, methods, status codes, headers, pagination and versioning.
- The HTTP details interviewers like to probe: PUT vs PATCH, idempotency, caching and concurrency headers, and keeping sensitive data out of the wrong places.
- GraphQL and gRPC: what problems they solve, what they cost, and how to choose between the three.
Start From the Entities
The API should fall out of the core entities you just listed. If your entities are User, Event, Ticket and Booking, your resources are almost certainly /users, /events, /events/{id}/tickets and /bookings. If you find yourself inventing an endpoint that doesn't map to any entity, either the endpoint is wrong or you missed an entity.
The second source is the functional requirements. Each core requirement ("users should be able to book a ticket") should map to one or two endpoints. Writing them side by side is a quick way to check you haven't forgotten anything:
Users should be able to view an event -> GET /events/{eventId}
Users should be able to search for events -> GET /events?query=...&city=...&cursor=...
Users should be able to book tickets -> POST /bookings
That's the whole structure of a typical interview answer. The rest is about getting the details right.
REST
REST (Representational State Transfer) models your system as a set of resources, each with a URL, that clients manipulate with a small fixed set of HTTP methods. It's the default choice for anything public-facing, because every language, tool, proxy, cache and browser already speaks HTTP.
Resources and URLs
A few conventions make a REST API read well:
- Nouns, not verbs.
POST /bookings, notPOST /createBooking. The method is the verb. - Plural collections, IDs for items.
/eventsis the collection,/events/123is one event. - Nest only for true ownership.
/events/123/ticketsmakes sense because tickets belong to an event. Avoid going deeper than one level (/users/1/events/2/tickets/3/seats); give important things their own top-level collection instead. - Query parameters for filtering, sorting and paging.
GET /events?city=nyc&sort=date&limit=20. The path identifies what; the query string narrows it down.
Some operations don't fit CRUD on a resource: "cancel a booking," "retry a payment," "publish a draft." There are two reasonable options. You can model the action as a state change (PATCH /bookings/42 with {"status": "cancelled"}) or as a sub-resource that you create (POST /bookings/42/cancellation). Both are fine. A verb-shaped endpoint like POST /bookings/42:cancel (the style Google's APIs use) is also acceptable if you're consistent. What matters is that you pick one and the semantics are clear.
HTTP Methods
Each method has two properties worth knowing by name, because interviewers ask about them:
- Safe: the request doesn't change server state. Caches, crawlers and prefetchers are allowed to send it freely.
- Idempotent: sending the same request twice has the same effect as sending it once. Clients and proxies can retry it after a timeout without fear.
| Method | Use | Safe | Idempotent |
|---|---|---|---|
GET |
Read a resource or collection | Yes | Yes |
POST |
Create a resource, or trigger an action | No | No |
PUT |
Replace a resource with the full body sent | No | Yes |
PATCH |
Partially update a resource | No | Not guaranteed |
DELETE |
Remove a resource | No | Yes |
Idempotency here is about the effect on the server, not the response. Deleting the same booking twice might return 204 and then 404, but the state after both calls is the same: the booking is gone.
The row that matters most is POST. Creating a booking or charging a card with POST is not safe to retry: if the response is lost, the client doesn't know whether the booking exists, and a naive retry creates two. The standard fix is an idempotency key: the client generates a unique ID per logical operation, sends it in an Idempotency-Key header, and the server stores the result of the first request under that key and returns it again on any retry. Stripe's API is the best-known example. The details of how to store and expire those keys are covered in /system-design/idempotency.
POST /bookings
Idempotency-Key: 6f1c2a9e-8d4b-4b7a-9c1e-2f0a7d3b5e11
Content-Type: application/json
{ "eventId": "evt_123", "seatIds": ["A12", "A13"] }
PUT vs PATCH
This is one of the most common HTTP follow-ups, and the answer has more substance than "PUT is full, PATCH is partial."
PUT replaces. The body is the complete new representation of the resource. Any field you leave out is, by the semantics of PUT, removed or reset to its default. That's what makes PUT idempotent: sending the same full representation twice leaves the resource in the same state. PUT can also create a resource at a URL the client chooses (PUT /users/42/avatar), which is handy when the client owns the ID.
PATCH modifies. The body describes a change, and the server applies it to the current state. There are two standard formats:
- JSON Merge Patch (RFC 7396,
Content-Type: application/merge-patch+json): send an object with only the fields to change. Anullvalue means "delete this field." Simple, and what most APIs actually do. Its limitation is that you can't set a field tonullon purpose, and you can't edit part of an array; arrays are replaced whole. - JSON Patch (RFC 6902,
Content-Type: application/json-patch+json): send a list of operations likeadd,remove,replace,moveandtestat JSON-pointer paths. More precise, andtestlets you make an operation conditional on a current value.
PATCH /users/42
Content-Type: application/merge-patch+json
{ "displayName": "Rui", "bio": null }
PATCH /users/42
Content-Type: application/json-patch+json
[
{ "op": "test", "path": "/version", "value": 7 },
{ "op": "replace", "path": "/displayName", "value": "Rui" },
{ "op": "add", "path": "/tags/-", "value": "admin" }
]
Is PATCH idempotent? It depends on the patch. "Set displayName to Rui" is idempotent. "Append admin to tags" or "increment loginCount" is not. That's why HTTP doesn't promise it, and why you should either keep patches to plain field assignments or protect them with a precondition.
Why it matters in a design. PUT has a classic concurrency bug: two clients both GET a profile, one changes the name, the other changes the bio, and both PUT their full copy back. The second write silently erases the first change. This is the lost update from /system-design/transactions, in HTTP form. PATCH with only the changed fields avoids most of it, and conditional requests (next section) avoid the rest.
When you write an update endpoint in an interview, use
PATCHwith only the fields that change, and say why: smaller payloads, and two clients editing different fields don't overwrite each other. If the interviewer pushes on concurrent edits to the same field, bring upETagandIf-Match.
Status Codes
You don't need all of them, but you should use the right family and a handful of specific ones:
- 2xx success:
200 OK,201 Created(with aLocationheader pointing to the new resource),202 Accepted(work queued, not done yet),204 No Content(success, nothing to return). - 3xx redirection:
301/308permanent redirect (308keeps the method and body),302/307temporary, and304 Not Modifiedfor cache revalidation. A URL shortener's choice between301and302is a real design decision: permanent redirects get cached by browsers, which saves traffic but hides clicks from your analytics. - 4xx client errors:
400malformed request,401 Unauthorized(really "unauthenticated": no valid credentials),403 Forbidden(authenticated, but not allowed),404,409 Conflict(state conflict, like a seat already taken),412 Precondition Failed(anIf-Matchdidn't match),422(well-formed but semantically invalid),429 Too Many Requests. - 5xx server errors:
500,502 Bad Gateway,503 Service Unavailable(often withRetry-After),504 Gateway Timeout.
The distinction between 4xx and 5xx matters for retries: a client should generally not retry a 4xx without changing the request, while 5xx and 429 are candidates for retry with backoff. For error bodies, the standard format is Problem Details (RFC 9457, application/problem+json), which gives every error a type, title, status and detail so clients can handle them consistently.
Headers That Do Real Work
Headers are where a lot of good API design lives, and naming the right one is a quick way to show depth.
Content negotiation: Content-Type says what the body is; Accept says what the client wants back. Accept-Encoding: gzip, br and the matching Content-Encoding let you compress responses, which often cuts JSON payloads by 70-90%.
Authentication: Authorization: Bearer <token> carries an access token on every request. Browser apps often use a session cookie instead. (How those tokens are issued and checked is the subject of /system-design/authentication-authorization.)
Caching: Cache-Control tells browsers and CDNs whether and how long they may cache a response:
Cache-Control: public, max-age=60, stale-while-revalidate=300 # event page, CDN-cacheable
Cache-Control: private, no-store # account page, never cache
Validators and conditional requests: the server returns an ETag (a version or hash of the resource) with each response. Clients then send it back:
If-None-Match: "v7"on aGET: if nothing changed, the server replies304 Not Modifiedwith no body. Cheap revalidation.If-Match: "v7"on aPUT,PATCHorDELETE: only apply the change if the resource is still at version 7, otherwise reply412 Precondition Failed. This is optimistic concurrency control over HTTP, the same version check you'd write asUPDATE ... WHERE version = 7.
Idempotency: Idempotency-Key on POST requests, as above.
Rate limiting: 429 responses should carry Retry-After, and many APIs also return remaining-quota headers (commonly X-RateLimit-Limit, X-RateLimit-Remaining and X-RateLimit-Reset; an IETF draft standardizes them as RateLimit fields). See /system-design/rate-limiter.
Tracing: traceparent (W3C Trace Context) propagates a trace ID through every service a request touches, so one slow request can be followed end to end. A Request-Id echoed in responses helps support teams find a request in the logs.
Pagination
Any endpoint that returns a list must be paginated, and interviewers will ask how. There are two main approaches.
Offset pagination: GET /events?limit=20&offset=40. Simple, and it supports "jump to page 7." But it has two problems. First, OFFSET 100000 makes the database read and discard 100,000 rows, so deep pages get slower and slower. Second, it's unstable: if a new item is inserted at the top while a user is paging, every item shifts down by one, and the user sees a duplicate on the next page (or misses one after a delete).
Cursor pagination: the response includes an opaque nextCursor that encodes where the page ended, typically the sort key of the last item. The next request passes it back:
GET /feed?limit=20&cursor=eyJ0IjoxNzAwMDAwMDAwLCJpZCI6OTg3fQ
-- cursor decodes to (created_at, id) of the last item on the previous page
SELECT * FROM posts
WHERE (created_at, id) < ($1, $2)
ORDER BY created_at DESC, id DESC
LIMIT 20;
With an index on (created_at, id), every page is an index seek, so page 5,000 is as fast as page 1, and inserts at the top don't shift anything. The id in the cursor breaks ties between items with the same timestamp. The cost is that you can't jump to an arbitrary page, which feeds, timelines, chat history and search results don't need anyway.
Make the cursor opaque (base64 of a small JSON blob, possibly signed). That way clients can't build their own cursors, and you can change what's inside later.
Default to cursor pagination in an interview for anything that grows without bound: feeds, messages, comments, transaction history. Mention offset only for small admin tables where "go to page N" is a real requirement.
Versioning and Evolution
APIs change, and clients you don't control (mobile apps that users never update, partner integrations) keep calling the old shape for years. The rules that keep you out of trouble:
- Additive changes are safe: new optional fields, new endpoints, new enum values (if clients were told to ignore unknown ones).
- Breaking changes need a new version: removing or renaming a field, changing a type, making an optional field required, changing what a status code means.
- Put the version somewhere explicit. A URL prefix (
/v1/events) is the most common and easiest to route and cache. A header (Accept: application/vnd.example.v2+json) or a date-based version header (the style Stripe uses) keeps URLs clean but is harder to test in a browser.
In practice, most teams version rarely and evolve additively most of the time.
Long-Running Operations and Bulk Work
Not every request finishes in a few hundred milliseconds. Transcoding a video, generating a report or importing a CSV can take minutes. Holding an HTTP connection open that long is fragile, so the standard pattern is:
POST /exportsreturns202 Acceptedwith aLocation: /exports/abcheader.- The client polls
GET /exports/abc(statuspending,running,done) or receives a webhook when it's done. - When done, the resource includes a link to the result, often a pre-signed S3 URL.
Uploads of large files follow the same spirit: the API hands out a pre-signed URL and the client uploads directly to object storage, so gigabytes of bytes never pass through your application servers.
Keeping Sensitive Data Safe
This is where a solid API answer becomes a senior one. A few rules cover most of what interviewers look for.
Never put secrets or personal data in the URL. URLs end up in places you don't control: server access logs, load balancer and CDN logs, browser history, analytics tools and the Referer header sent to third-party sites. A password reset token, API key, email address or social security number in a query string will leak. Put credentials in the Authorization header and sensitive inputs in the request body, which proxies and logs don't record by default.
# Bad: the token and email end up in every access log on the path
GET /reset-password?token=8f2c...&[email protected]
# Better
POST /password-resets/confirm
Content-Type: application/json
{ "token": "8f2c...", "newPassword": "..." }
Don't trust identity from the request body. A common mistake in interview APIs is POST /bookings { "userId": 42, ... }. If the server uses that userId, any user can book as any other user. The caller's identity must come from the authenticated session or token, which the server verifies. The body says what to do; the token says who is doing it.
Check ownership on every object. GET /bookings/987 must confirm that booking 987 belongs to the caller (or that the caller is allowed to see it). Forgetting this is called broken object-level authorization (also known as IDOR, insecure direct object reference), and it's consistently near the top of OWASP's API security risks. Random, unguessable IDs (UUIDs) make enumeration harder, but they don't replace the check.
Return only what the client needs. Don't serialize your database row straight into the response. That's how password hashes, internal flags and other users' emails leak. Use explicit response types, and mask sensitive fields ("card": "•••• 4242").
Use TLS everywhere, including between internal services where you can, and set Cache-Control: no-store on responses that contain personal data, so shared caches and CDNs never keep a copy.
Be careful with error messages. "No account with that email" on a login or reset form tells an attacker which emails are registered. Return the same response either way.
If your API has a
userIdin the body or path of a "my stuff" endpoint, expect your interviewer to ask "what stops me from passing someone else's ID?" Get ahead of it: useGET /me/bookingsor derive the user from the token, and say that every object read checks ownership.
GraphQL
GraphQL is a query language for APIs. Instead of many endpoints with fixed responses, you expose one endpoint (usually POST /graphql) and a typed schema, and each client asks for exactly the fields it needs:
query EventPage($id: ID!) {
event(id: $id) {
name
startsAt
venue { name city }
tickets(first: 10, availableOnly: true) {
edges { node { section row price } }
pageInfo { endCursor hasNextPage }
}
}
}
That one request replaces what might be three REST calls (/events/{id}, /venues/{id}, /events/{id}/tickets), and the response contains only the fields asked for. GraphQL was created to solve two specific problems that REST has with rich client UIs:
- Under-fetching: a screen needs data from several resources, so the client makes several round trips. On a mobile network with 100-300 ms of latency per round trip, that adds up quickly.
- Over-fetching: each endpoint returns everything, even when the screen needs two fields.
But what is actually happening under the hood? The GraphQL server parses the query, validates it against the schema, and then calls a resolver function for each field. event is resolved by loading the event, venue by loading that event's venue, tickets by querying tickets for that event. Each resolver can talk to a different backend: a database, a REST service, a gRPC service. That's why GraphQL is often deployed as an aggregation layer in front of many services, or as a backend for frontend (covered in /system-design/microservice-patterns).
The resolver model creates GraphQL's best-known performance trap, the N+1 problem. A query for 50 events with their venues calls the venue resolver 50 times, which naively means 50 database queries after the first one. The standard fix is DataLoader-style batching: within one request, collect every venue ID the resolvers asked for, then load them all with one WHERE id IN (...) query.
GraphQL's trade-offs are worth stating plainly:
- Caching is harder. Most queries are
POSTs to one URL, so HTTP caches and CDNs can't cache them by URL. Persisted queries (the client sends a hash of a pre-registered query, possibly viaGET) restore some of this. Client libraries like Apollo and Relay cache normalized objects on the device. - Expensive queries are easy to write. A client can ask for users, their friends, their friends' friends and all their posts in one deeply nested query. Public GraphQL APIs need depth limits, query cost analysis and per-client budgets (GitHub's GraphQL API rate-limits by computed query cost rather than request count).
- Errors don't map to status codes. A GraphQL response usually returns
200with adataobject and anerrorsarray, because part of a query can succeed while another part fails. Monitoring has to look inside the body. - Authorization moves to the field level. With one endpoint, you can't protect routes; each resolver (or a layer in front of the data) has to check access.
GraphQL shines for product clients with many screens and evolving data needs, and for aggregating many backends behind one schema. It's usually overkill for a simple public API, service-to-service calls or file transfer. The technology itself is covered in /system-design/graphql.
gRPC
gRPC is a remote procedure call framework. You define services and messages in Protocol Buffers (protobuf), generate client and server code in your languages, and call remote methods as if they were local functions:
syntax = "proto3";
service Inventory {
rpc ReserveSeats(ReserveRequest) returns (ReserveResponse);
rpc WatchAvailability(WatchRequest) returns (stream AvailabilityUpdate);
}
message ReserveRequest {
string event_id = 1;
repeated string seat_ids = 2;
string idempotency_key = 3;
}
message ReserveResponse {
string reservation_id = 1;
int64 expires_at_ms = 2;
}
What gRPC gives you:
- A compact binary format. Protobuf messages are typically several times smaller than the equivalent JSON and faster to encode and decode, which matters when services make millions of internal calls per second.
- A strict, generated contract. Clients and servers share the
.protofile, so a type mismatch is a compile error, not a production incident. The field numbers (= 1,= 2) are what go over the wire, which is what makes evolution safe: you can add new fields and old clients ignore them, as long as you never reuse or renumber a field. - HTTP/2 underneath. Many concurrent calls are multiplexed over one connection, with header compression.
- Streaming. Besides normal unary calls, gRPC supports server streaming, client streaming and bidirectional streaming, which suits things like live updates between services or uploading telemetry.
- Deadlines. A caller sets a deadline ("this call must finish within 300 ms"), and gRPC propagates the remaining time to downstream calls. When it expires, the work is cancelled everywhere. This is one of the most useful resilience features you can name (see /system-design/resilience-patterns).
The costs:
- Browsers can't call it directly. Browsers don't expose the HTTP/2 framing gRPC needs, so you need gRPC-Web with a proxy such as Envoy, or a REST/GraphQL layer at the edge.
- It's not human-readable. You can't debug with
curland a glance at the body; you need tools likegrpcurland the.protofiles. - Load balancing needs care. Because a client keeps one long-lived HTTP/2 connection and sends all its calls over it, a plain layer-4 load balancer pins every call from that client to one backend. You need a layer-7 proxy (Envoy, a service mesh) or client-side load balancing that spreads individual calls. This is a classic follow-up question; see /system-design/load-balancer.
gRPC is the common choice for internal service-to-service communication where performance and strong contracts matter. The technology itself is covered in /system-design/grpc.
Choosing Between Them
| REST | GraphQL | gRPC | |
|---|---|---|---|
| Best for | Public APIs, simple CRUD, anything cacheable | Product UIs with varied data needs, aggregating many backends | Internal service-to-service calls, streaming between services |
| Format | Usually JSON over HTTP/1.1 or HTTP/2 | JSON over HTTP, one endpoint | Protobuf over HTTP/2 |
| Contract | OpenAPI (optional) | Schema (required) | .proto (required, generated code) |
| HTTP caching | Excellent (GET + Cache-Control + CDN) |
Poor without persisted queries | None at the HTTP layer |
| Browser support | Native | Native | Needs gRPC-Web proxy |
| Main pitfalls | Over/under-fetching, chatty clients | N+1 resolvers, costly queries, caching | Debuggability, L7 load balancing |
These aren't exclusive. A very common real-world shape is all three: REST (or GraphQL) at the edge for clients, an API gateway handling authentication and rate limits, and gRPC between internal services.
What about real-time features like chat, live scores or collaborative editing? None of the three request-response styles handles server push well on its own. Those use WebSockets, Server-Sent Events or long polling, covered in /system-design/real-time-updates. In your API section, list them separately: "GET /chats/{id}/messages for history, plus a WebSocket at /ws for new messages."
API Design in an Interview
Writing the API Section
Keep it short and precise. For each core requirement, write the method, the path, the important parameters and what comes back. A good API section for a ticketing system fits in a few lines:
GET /events/{eventId} -> Event (with venue, price ranges)
GET /events?query=&city=&from=&cursor= -> { events: Event[], nextCursor }
POST /bookings -> Booking
headers: Authorization, Idempotency-Key
body: { eventId, seatIds[] }
GET /me/bookings?cursor= -> { bookings: Booking[], nextCursor }
Notice what's in there: the user comes from the Authorization header, not the body; the booking POST carries an idempotency key; both lists use cursors. Each of those is a small decision that heads off a follow-up question.
Don't spend more than about five minutes here. Interviewers care much more about the high-level design and deep dives. If you're not sure whether they want REST or something else, say "I'll use REST since this is a client-facing API" and move on.
Which Style When
- REST is the default for anything a client, partner or browser calls. Pick it unless there's a reason not to.
- GraphQL when the interviewer emphasizes many client types with different data needs, a mobile app on slow networks, or a UI composed from many backend services.
- gRPC for internal calls between your own services, especially high-volume or latency-sensitive ones, and for streaming between services.
- WebSockets / SSE alongside any of them when the server must push updates.
Common Follow-ups
- "What's the difference between PUT and PATCH?" Replace versus modify;
PUTis idempotent andPATCHisn't guaranteed to be;PATCHavoids lost updates on different fields;If-Matchhandles the same field. - "What happens if the client retries the booking request?" Without protection, a duplicate booking. With an
Idempotency-Key, the server returns the original result. - "How do you paginate this?" Cursor-based, with the sort key and a tiebreaker in an opaque cursor, backed by a composite index.
- "How would you handle a breaking change?" Additive changes first; a new version only when necessary; keep the old one running until clients migrate.
- "Why not gRPC everywhere?" Browser support, debuggability and HTTP caching. It's great internally, awkward at the edge.
- "How do you stop users from reading other users' data?" Identity from the token, ownership checks on every object, no secrets in URLs, minimal response fields.
Summary
API design is a small part of the interview with an outsized effect. Start from your entities and functional requirements, and map each requirement to one or two endpoints. In REST, use nouns for resources and methods for verbs, know which methods are safe and idempotent, and protect non-idempotent POSTs with idempotency keys. Prefer PATCH for partial updates, and use ETag with If-Match when concurrent edits matter. Use the right status codes, and let headers do the work they're designed for: caching, conditional requests, authentication, rate limits and tracing. Paginate unbounded lists with cursors.
Treat the API as your security boundary: identity comes from the token, every object read checks ownership, and secrets and personal data stay out of URLs and out of responses that don't need them. Finally, choose the style to fit the caller: REST for public and client APIs, GraphQL for rich UIs over many backends, gRPC for fast, strongly typed internal calls, and WebSockets or SSE whenever the server needs to push.