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.
Video lesson · Chapter 1 of 5
What can a client safely repeat?
Theory
Read or listen first. About 2 min.
What it is
REST stands for Representational State Transfer. It is an architectural style, which means a set of rules for designing a system, and not a product, a protocol or a file format. A resource is anything worth naming, such as a user or an order. A representation is a copy of its state that travels over the network, often as JSON.
In practice a REST API is an HTTP API that names resources with URLs, acts on them with standard methods such as GET, PUT and DELETE, reports the result with a status code, and keeps no conversation in the server's memory between requests.
Why it exists
The web already had software that understands HTTP: browsers, caches, load balancers, proxies, logs and libraries in every language. An API that follows the same rules gets all of that for nothing. A cache can keep a GET, and a client can safely repeat a DELETE, without knowing what the product does.
The price is that the server decides the shape of each answer, and one screen may need several requests. That trade is often good for public APIs and plain create, read, update and delete work. It is weaker for streams, and for screens that need many related things at once.
A short history
2000
Roy Fielding describes REST in a doctoral dissertation at the University of California, Irvine, as the style behind the design of HTTP.
2008
Fielding writes that an API must be driven by hypertext to be called REST. Most APIs that use the name stop short of that.
March 2010
RFC 5789 adds PATCH, a method for partial changes that is neither safe nor idempotent by definition.
June 2022
RFC 9110 gathers the meaning of HTTP methods, status codes and headers in one document for every HTTP version.
July 2023
RFC 9457 replaces RFC 7807 as the standard shape for error bodies.
June 2026
RFC 10008 publishes QUERY, a safe and idempotent method that carries a body: a search that does not have to pretend to be a POST.
Words to know
- Resource
- A thing with a name and an address: one user, or the collection of users.
- Representation
- A copy of a resource's state in some format, such as JSON, XML or HTML.
- Safe method
- A method the client uses only to read: GET, HEAD, OPTIONS, TRACE and QUERY.
- Idempotent method
- Doing it twice leaves the server as doing it once: the safe methods, PUT and DELETE.
- Stateless
- Each request carries all the server needs to understand it.
- ETag
- A label for one version of a representation.
- HATEOAS
- Hypermedia as the engine of application state: answers carry links to what can be done next.
Understand it
Start here
The vending wall
A hall has a wall of compartments. Each one has a label, and each one has the same four handles. Once you know the handles, you can use any compartment, including one that was added this morning.
The labels belong to the product. The handles belong to everyone.
The style
Six constraints, and what each one buys
Fielding's dissertation builds REST by adding constraints one at a time. API design introduces them. Here is what you get for obeying each one, and what breaking it costs.
| Constraint | What it buys | A common way to break it |
|---|---|---|
| Client and server | Each side can change alone | Pages that read the database directly |
| Stateless | Any server can answer any request | Sessions kept in one server's memory |
| Cacheable | Fewer trips and less load | No cache headers, or POST for every read |
| Uniform interface | General tools work everywhere | One URL called /api, with the action in the body |
| Layered system | Gateways and balancers fit in the middle | Clients tied to one server address |
| Code on demand (optional) | The server can extend the client | Rarely used by JSON APIs |
Why teams choose it
Simple
Plain HTTP requests. A browser or a command-line tool is enough to try it.
Scales out
With no session in memory, you add servers behind a load balancer.
Flexible
Any language and any format: JSON, XML, HTML or an image.
Fast when cached
Answers can be kept in the browser, the CDN and the gateway.
Everywhere
Client libraries, documentation tools and people who know it are easy to find.
Security that exists
TLS, OAuth 2 and API keys already work over HTTP.
Addresses
Resources and their URLs
A URL names a thing, so it is a noun. The action is the method. Use one style for the whole API and keep nesting shallow.
The library seat service
| Request | Meaning | Answer |
|---|---|---|
GET /seats?free=true | List free seats | 200 and a page |
GET /seats/12 | Read one seat | 200, or 404 |
POST /bookings | Create a booking | 201 and Location |
PUT /profiles/7 | Replace a profile | 200 or 204 |
PATCH /bookings/9 | Change the end time | 200 |
DELETE /bookings/9 | Cancel | 204 |
POST /bookings/9/check-in | An action that is not a plain edit | 200 |
Reads well
/users/7/orders- Plural nouns everywhere
- Filters in the query string
- At most one level of nesting
Causes trouble
/getUserOrders?id=7/userhere and/ordersthereGET /orders/9/delete: a crawler would delete things/a/1/b/2/c/3/d/4
Verbs
What each method promises
Safe means the client asks only to read. Idempotent means a repeat leaves the same state. The second promise is about the server's state, not the answer: the second DELETE may say 404, and DELETE is still idempotent.
Promises made by HTTP (RFC 9110, RFC 5789, RFC 10008)
| Method | Safe | Idempotent | Use |
|---|---|---|---|
| GET | Yes | Yes | Read |
| HEAD | Yes | Yes | Read the headers only |
| POST | No | No | Create, or process |
| PUT | No | Yes | Replace all, or create at a known URL |
| PATCH | No | Not by itself | Change part |
| DELETE | No | Yes | Remove |
| QUERY | Yes | Yes | Read, with a body. New in 2026, so check support on your path |
// The stored profile{ "name": "Asha", "city": "Pune", "phone": "555-0100" }// PUT with { "name": "Asha", "city": "Delhi" }// replaces everything, so phone is gone{ "name": "Asha", "city": "Delhi" }// PATCH with Content-Type: application/merge-patch+json// and { "city": "Delhi", "phone": null }// null removes a member, anything not named stays{ "name": "Asha", "city": "Delhi" }Which method?
Answers
Status codes and headers
The codes worth knowing
| Code | Means | The client should |
|---|---|---|
| 200 OK | Worked, body attached | Use it |
| 201 Created | Made something new | Read Location |
| 202 Accepted | Will be done later | Follow the status URL |
| 204 No Content | Worked, no body | Go on |
| 304 Not Modified | Your copy is still good | Use the copy |
| 400 Bad Request | The request is malformed | Fix it, do not retry |
| 401 Unauthorized | No valid credentials | Sign in or refresh, then retry once |
| 403 Forbidden | Known, but not allowed | Stop |
| 404 Not Found | No such resource, or you may not know of it | Stop |
| 405 Method Not Allowed | Wrong handle for this door | Read Allow |
| 409 Conflict | Clashes with the current state | Reload and decide |
| 412 Precondition Failed | The version you named is old | Reload and retry |
| 422 Unprocessable Content | Well formed, but breaks a rule | Fix the fields |
| 429 Too Many Requests | Over the limit | Wait for Retry-After |
| 500 Internal Server Error | A fault on our side | Retry only if idempotent |
| 503 Service Unavailable | Overloaded or in maintenance | Wait, with backoff |
Five headers that do most of the work
| Header | Says | Example |
|---|---|---|
| Content-Type | The format of this body | application/json |
| Accept | The formats I can read | application/json |
| Authorization | Who I am | Bearer and a token |
| Cache-Control | Who may keep this, for how long | max-age=3600 |
| ETag | The version of this representation | "v7" |
Content negotiation lets one resource have several formats. The client sends Accept, and the server answers in one of them, names it in Content-Type, and adds Vary: Accept so that a cache keeps them apart.
HTTP/1.1 422 Unprocessable ContentContent-Type: application/problem+json{ "type": "https://api.example.com/problems/validation", "title": "Some fields are not valid", "status": 422, "detail": "email must contain an @", "errors": { "email": ["must contain an @"] }}Error design has its own page: API error handling.
The path
One request, end to end
A stateless API behind shared HTTP parts
- 1
The client sends a request
Method, URL, headers such as Authorization and Content-Type, and sometimes a body.
- 2
The load balancer picks a server
Round robin or least connections, among servers that pass health checks. TLS often ends here. Sticky sessions would tie a client to one server and bring hidden state back.
- 3
The gateway checks it
It verifies the token, applies a limit such as 100 requests a minute (an example, not a standard), and routes. See API gateway.
- 4
The server looks in the cache
For a GET, the key is built from the URL and its parameters. A hit skips the database. Entries expire, and writes must remove them.
- 5
The server uses the database
Through a connection pool, with a transaction for a write.
- 6
The answer goes back
Status code, caching headers and a body.
A read that costs almost nothing
A cache may keep a successful GET even without headers, for a time it guesses. So always set Cache-Control, including no-store for private answers. Full rules: API caching.
What a 304 saves
Writes
Do not lose an update
Two people open the same profile, and both press save. With a plain PUT the second save wipes out the first without a word. A conditional write fixes it: say which version you edited.
If-Match stops the second writer
A create has another problem. The answer is lost, the client repeats the POST, and now there are two. Let the client send a unique Idempotency-Key, store the key with the result, and give the same answer to a repeat. The header is widely used and is still an IETF draft. Stripe's version 1 API may remove keys once they are 24 hours old. Details: idempotency.
Lists
Pages, filters and sorting
A collection without a limit grows until it breaks. Give every list a default page and a hard maximum, and tell the client how to continue. Choosing between offset and cursor is the subject of API pagination. Filters are in search and filtering.
{ "data": [{ "id": 11, "name": "Asha" }, { "id": 12, "name": "Lee" }], "pagination": { "page": 2, "limit": 10, "total": 37, "totalPages": 4, "hasNext": true, "hasPrev": true }, "links": { "self": "/users?page=2&limit=10", "first": "/users?page=1&limit=10", "last": "/users?page=4&limit=10", "next": "/users?page=3&limit=10", "prev": "/users?page=1&limit=10" }}Cost of a full walk
Maturity
How much REST is enough?
Leonard Richardson's model, described by Martin Fowler, has four levels. Most public APIs stop at level 2.
| Level | You have | You gain |
|---|---|---|
| 0 | One URL, everything is a POST | A tunnel through HTTP |
| 1 | Many resources | Addresses |
| 2 | Methods and status codes | Caching, safe retries, general tools |
| 3 | Links in answers (HATEOAS) | Clients follow links instead of building URLs |
{ "id": 9, "seat": 12, "state": "BOOKED", "_links": { "self": { "href": "/bookings/9" }, "check-in": { "href": "/bookings/9/check-in" }, "cancel": { "href": "/bookings/9" } }}Change
Contract, versions and the end of life
OpenAPI describes the paths, parameters and schemas of an HTTP API in one file. The current line is 3.2. From it you can make documentation, clients, test servers and a check in CI that fails on a breaking change.
Safe to add
- A new optional field in an answer
- A new optional parameter
- A new path
- A new value, if clients were told to accept unknown ones
Breaks clients
- Removing or renaming a field
- Changing a type
- Making a parameter required
- Giving an old status code a new meaning
Retiring something
See API versioning. One worked example: GitHub takes the version as a date in the X-GitHub-Api-Version header, uses 2022-11-28 when the header is missing, and supports a version for 24 months after a newer one appears.
Build it
A service in FastAPI, and a client
from fastapi import FastAPI, HTTPException, Responsefrom pydantic import BaseModelapp = FastAPI()class UserIn(BaseModel): name: str email: strclass User(UserIn): id: intusers: dict[int, User] = {} # a database in real lifenext_id = 1def find(user_id: int) -> User: if user_id not in users: raise HTTPException(status_code=404, detail="User not found") return users[user_id]@app.get("/api/users")def list_users(limit: int = 20) -> list[User]: return list(users.values())[: max(1, min(limit, 100))]@app.get("/api/users/{user_id}")def get_user(user_id: int) -> User: return find(user_id)@app.post("/api/users", status_code=201)def create_user(body: UserIn, response: Response) -> User: global next_id user = User(id=next_id, **body.model_dump()) users[user.id] = user next_id += 1 response.headers["Location"] = f"/api/users/{user.id}" return user@app.put("/api/users/{user_id}")def replace_user(user_id: int, body: UserIn) -> User: find(user_id) users[user_id] = User(id=user_id, **body.model_dump()) return users[user_id]@app.delete("/api/users/{user_id}", status_code=204)def delete_user(user_id: int) -> None: find(user_id) del users[user_id]import osimport requestsAPI = "https://api.example.com"http = requests.Session() # reuses the connectionhttp.headers["Authorization"] = "Bearer " + os.environ["API_TOKEN"]TIMEOUT = (3, 10) # connect, read, in secondsdef get_user(user_id): r = http.get(f"{API}/users/{user_id}", timeout=TIMEOUT) if r.status_code == 404: return None r.raise_for_status() # raises for 4xx and 5xx return r.json()def create_user(name, email, key): r = http.post(f"{API}/users", json={"name": name, "email": email}, headers={"Idempotency-Key": key}, timeout=TIMEOUT) r.raise_for_status() return r.json()def replace_user(user_id, body, etag): r = http.put(f"{API}/users/{user_id}", json=body, headers={"If-Match": etag}, timeout=TIMEOUT) r.raise_for_status() # 412 means reload first return r.json()def patch_user(user_id, changes): r = http.patch(f"{API}/users/{user_id}", json=changes, timeout=TIMEOUT) r.raise_for_status() return r.json()def delete_user(user_id): r = http.delete(f"{API}/users/{user_id}", timeout=TIMEOUT) return r.status_code in (204, 404) # gone either wayOperate
Running it in production
| Watch | Because | Do |
|---|---|---|
| Rate, errors and p99 per route | An average hides one slow route | Group by route template, not by raw URL |
| 4xx by code | A jump in 401 or 422 is often a client release | Alert on change, not on zero |
| 429 and Retry-After | Clients must slow down | Publish the limits |
| Request and body size | One huge body can fill memory | Set limits at the gateway |
| Cache hit ratio | A new query parameter can end all hits | Normalise the key |
| Calls to deprecated routes | You cannot remove what is still used | Count by client |
Good
- Simple: familiar HTTP.
- Cacheable: GET works with every cache.
- Scales: stateless servers.
- Universal: any language and client.
Costs
- Over-fetching: fields nobody on this screen needs.
- Under-fetching: several requests for one screen.
- No push: request and response only.
- Versioning: long-lived clients make change slow.
Decide
REST, or something else?
Beside its neighbours
| REST | GraphQL | gRPC | WebSockets | |
|---|---|---|---|---|
| Address | Many URLs | One endpoint | Service methods | One open connection |
| Shape of the answer | Server decides | Client decides | Schema decides | You decide |
| Format | Often JSON | Usually JSON | Protobuf by default | Any message |
| HTTP caching | Built in | Needs GET and hashed queries | Not used | None |
| Server push | No | Subscriptions | Streams | Yes, both ways |
| From a browser | Directly | Directly | gRPC-Web, usually with a proxy | Directly |
| Good for | Public APIs, CRUD | Screens with varied needs | Calls between services | Chat, live updates |
Choose REST when
- The API is public and must be easy to adopt
- The work is create, read, update and delete
- Caching matters
- Web and mobile clients use it
- Clients use many languages
- Services call each other and simplicity beats speed
Look elsewhere when
- Both sides must talk at any time: WebSockets
- Internal calls are many and tight: gRPC
- Each screen needs a different mix: GraphQL
- The server streams updates: server-sent events
- Every byte and millisecond is counted
Side by side in depth: REST, GraphQL and gRPC. Live updates: real-time APIs.
Summary
The whole topic in one minute.
REST gives every resource an address and acts on it with a few methods that mean the same everywhere. GET reads, POST creates or processes, PUT replaces, PATCH changes part, DELETE removes. Status codes report the result and headers carry format, identity and caching.
Its strength is what the middle of the network can do with those shared rules: cache, retry, balance and log. Its costs are fixed answer shapes and extra round trips. Protect updates with If-Match, creates with an idempotency key, collections with limits, and clients with additive change and a published end date.
- Resources have addresses, and methods have shared meanings.
- Safe and idempotent are promises that caches and retry code rely on.
- Stateless servers make scaling out simple.
- Use If-Match for updates and an idempotency key for creates.
- Limit every list, describe the API with OpenAPI, and change it by adding.