APIs and REST
Overview
Every system you design has an API: the contract between clients and your servers, or between your own services. In interviews, writing down the API early is one of the fastest ways to make a vague problem concrete. This lesson covers how to design clean HTTP APIs in the REST style, and briefly how the alternatives differ.
Anatomy of a REST call
A request has four parts:
- a method that says what to do,
- a path that names the resource,
- headers with metadata such as authentication and content type,
- an optional body, usually JSON.
The response carries a status code, headers and usually a body.
Resources and methods
REST (representational state transfer) models an API as resources, the nouns of your domain, each with a URL:
/v1/users/17
/v1/users/17/orders
/v1/orders/981HTTP methods are the verbs:
| Method | Meaning | Safe? | Idempotent? |
|---|---|---|---|
| GET | Read a resource or a list | Yes | Yes |
| POST | Create a resource, or trigger an action | No | No |
| PUT | Replace a resource entirely | No | Yes |
| PATCH | Change some fields | No | Usually not guaranteed |
| DELETE | Remove a resource | No | Yes |
Good habits:
- Use nouns in paths and let the method be the verb:
POST /orders, notPOST /createOrder. - Nest only for clear ownership:
/users/17/ordersreads well; four levels deep does not. - Take the current user from the auth token, not from the URL, so one user can’t read another user’s data by editing a number.
Idempotency: making retries safe
An operation is idempotent if doing it twice has the same effect as doing it once. DELETE /orders/981 is idempotent: after the first call the order is gone, and the second call changes nothing.
POST /orders is not. Imagine a phone on a bad connection: it sends the order, the server creates it, but the response is lost. The app retries, and now the customer has two orders and is charged twice.
The standard fix is an idempotency key: the client generates a unique ID for each logical action and sends it in a header. The server stores the key with the result; if the same key arrives again, it returns the stored result instead of doing the work again. Payment APIs rely on this, and you’ll use it in the payment case study.
Status codes
Status codes tell the client what to do next:
- 2xx, success.
200 OK,201 Created(with aLocationheader),204 No Content. - 4xx, the client’s fault.
400bad input,401not signed in,403not allowed,404not found,409conflict,429too many requests. Retrying the same request won’t help, except for 429. - 5xx, the server’s fault.
500bug,502/504a server behind the gateway failed or timed out,503overloaded or down for maintenance. Retrying later, with backoff, may succeed.
Pagination
Never return an unbounded list. There are two common styles:
- Offset pagination:
GET /posts?limit=20&offset=40. Simple and allows jumping to page 7, but slow for large offsets (the database still walks past the skipped rows), and items shift if new ones are added while the user scrolls. - Cursor pagination:
GET /posts?limit=20&cursor=eyJpZCI6.... The cursor encodes where the last page ended (for example the last item’s timestamp and ID). It stays fast and stable on huge, changing lists such as feeds, at the cost of not jumping to arbitrary pages.
For feeds, timelines and anything large, choose cursors.
Versioning and evolution
Clients, especially mobile apps, can’t all update at once, so a public API must keep working for old clients.
- Add fields freely; clients should ignore fields they don’t know.
- Never remove or rename a field, or change its meaning, in place.
- For breaking changes, release a new version (
/v2/...or a version header) and keep the old one running until clients have moved.
REST, GraphQL and gRPC
REST is the default for public APIs, but you should know the alternatives:
- GraphQL: clients ask for exactly the fields they need in one request. Great for apps with many screens needing different data; harder to cache and to protect from expensive queries.
- gRPC: compact binary messages over HTTP/2 with a strict schema. Fast and well suited to service-to-service calls inside your system; less convenient for browsers.
Week 5 compares these in more detail. In interviews, REST-style endpoints are almost always fine for the client API.
Writing the API in an interview
After clarifying requirements, list the core endpoints in a few lines, for example for a URL shortener:
POST /v1/urls {"long_url": "...", "alias": "optional"} -> 201 {"short_url": "..."}
GET /{code} -> 301/302 redirect to the long URLThis takes two minutes, makes the scope concrete and drives your data model.
Recap
A good HTTP API names resources with nouns, uses methods for actions, returns meaningful status codes, paginates every list, evolves without breaking clients and makes retries safe with idempotency. Sketching the API early in an interview turns a vague prompt into something you can design against.
Design a small API
Design the REST API for a simple to-do app where users have lists and each list has items. Users must be able to create a list, see all their lists, add an item, mark an item done, delete an item, and see a list's items 20 at a time. For each endpoint give the method, path, a short request body (if any) and the success status code.
Create a list:
Get my lists:
Add an item:
Mark an item done:
Delete an item:
Get items in a list (paginated):Create a list: POST /v1/lists {"name": "Groceries"} -> 201 Created
Get my lists: GET /v1/lists -> 200 OK
Add an item: POST /v1/lists/{listId}/items {"text": "Milk"} -> 201 Created
Mark an item done: PATCH /v1/lists/{listId}/items/{itemId} {"done": true} -> 200 OK
Delete an item: DELETE /v1/lists/{listId}/items/{itemId} -> 204 No Content
Get items: GET /v1/lists/{listId}/items?limit=20&cursor=abc123 -> 200 OK
response: {"items": [...], "next_cursor": "def456"}
Notes:
- The user comes from the auth token, not the URL, so users can't read each other's lists.
- Cursor pagination stays correct when items are added while the user scrolls.
- POST requests can accept an Idempotency-Key header so a retried request
doesn't create a duplicate list or item.
- Asking for another user's list returns 404 (or 403); a bad body returns 400.Summary
- REST models the API as resources (nouns in the URL) acted on by HTTP methods (GET, POST, PUT, PATCH, DELETE).
- GET, PUT and DELETE are idempotent; POST is not, so use an idempotency key when retries could create duplicates.
- Status codes tell the client what to do next: 2xx success, 4xx fix the request, 5xx and 429 retry later.
- Prefer cursor pagination over offsets for large or changing lists.
- Version public APIs (for example /v1/) and evolve them without breaking existing clients.