REST
easy 26 minREST is a style for network APIs: everything worth naming gets an address, and a small shared set of HTTP methods acts on it.
See it run
What each method promises, how a read is answered, and how writes stay safe when people and networks interfere.
Operations
Read the promises
Three questions about each method. The answers decide what caches and retry code may do.
Step 1 of 5
GET
| safe | repeatable | cache keeps it | |
|---|---|---|---|
| GET | yes | yes | yes |
| POST | no | no | rarely |
| PUT | no | yes | no |
| PATCH | no | no promise | no |
| DELETE | no | yes | no |
GET reads and nothing else
Safe, so a browser may prefetch it. Idempotent, so a client may repeat it. A cache may keep it.
Step 1: GET
SAFE = {"GET", "HEAD", "OPTIONS"}IDEMPOTENT = SAFE | {"PUT", "DELETE"}def may_repeat(method, has_key=False): return method in IDEMPOTENT or has_key- Extra trip
- None
- Guards against
- Surprises
- Where it is written
- RFC 9110 and RFC 5789
Idempotent speaks about the state on the server. The answers of two calls may differ.
In the real world
The same rest doing real jobs. Pick one and step through it.
A profile screen needs a user, their orders, reviews and points. Count the trips.
Step 1 of 4
Four endpoints
requests
user · orders · reviews · points
4 requests
The server decides each shape, so the screen asks four times.
Step 1: Four endpoints
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Writing on a GET
criticalPrefetching, crawlers and retries may call a GET at any time.
WrongGET /orders/9/cancelRightPOST /orders/9/cancel200 for a failure
majorCaches, monitors and clients see a success. The error rate on the dashboard stays at zero.
Wrong200 { "ok": false, "error": "not found" }Right404 { "title": "Not found", "status": 404 }Checking the version in a separate read
criticalAnother writer can slip in between the read and the write.
Wrongif load(id).version == v: save(id, body)RightUPDATE ... WHERE id = :id AND version = :v-- 0 rows changed means 412Lists without a maximum
majorOne client asking for everything can fill memory and hold a database connection for minutes.
Wronglimit = int(request["limit"])Rightlimit = min(max(int(request["limit"]), 1), 100)
Interview tips
How to explain it
- Resources have addresses.
- A few methods mean the same everywhere.
- So caches, proxies and retry code can help.
Before you ship an endpoint
- Right method and right status code?
- What happens if it is called twice?
- Who may cache the answer, and for how long?
Reach for it when
- The API is public.
- The work is mostly create, read, update and delete.
- Reads repeat.
Look elsewhere when
- The server must push.
- Services exchange many small calls.
- Each screen wants another shape.