AlgoViz

REST

easy 26 min

REST 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?

0:00 / 4:29

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

  1. 2000

    Roy Fielding describes REST in a doctoral dissertation at the University of California, Irvine, as the style behind the design of HTTP.

  2. 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.

  3. March 2010

    RFC 5789 adds PATCH, a method for partial changes that is neither safe nor idempotent by definition.

  4. June 2022

    RFC 9110 gathers the meaning of HTTP methods, status codes and headers in one document for every HTTP version.

  5. July 2023

    RFC 9457 replaces RFC 7807 as the standard shape for error bodies.

  6. 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.

Same four handles on every door
SNACKSall of themLNSESNACK 1LNSESNACK 2LNSELNSELlookNnewSswapEemptyOne wall, four handles

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.

ConstraintWhat it buysA common way to break it
Client and serverEach side can change alonePages that read the database directly
StatelessAny server can answer any requestSessions kept in one server's memory
CacheableFewer trips and less loadNo cache headers, or POST for every read
Uniform interfaceGeneral tools work everywhereOne URL called /api, with the action in the body
Layered systemGateways and balancers fit in the middleClients tied to one server address
Code on demand (optional)The server can extend the clientRarely 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

RequestMeaningAnswer
GET /seats?free=trueList free seats200 and a page
GET /seats/12Read one seat200, or 404
POST /bookingsCreate a booking201 and Location
PUT /profiles/7Replace a profile200 or 204
PATCH /bookings/9Change the end time200
DELETE /bookings/9Cancel204
POST /bookings/9/check-inAn action that is not a plain edit200
The last row is normal. When a verb does not fit create, read, update or delete, name the action as a sub-resource of the thing it acts on.

Reads well

  • /users/7/orders
  • Plural nouns everywhere
  • Filters in the query string
  • At most one level of nesting

Causes trouble

  • /getUserOrders?id=7
  • /user here and /orders there
  • GET /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)

MethodSafeIdempotentUse
GETYesYesRead
HEADYesYesRead the headers only
POSTNoNoCreate, or process
PUTNoYesReplace all, or create at a known URL
PATCHNoNot by itselfChange part
DELETENoYesRemove
QUERYYesYesRead, with a body. New in 2026, so check support on your path
JSON
// 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" }
JSON Merge Patch (RFC 7396). JSON Patch (RFC 6902) is the other standard form: a list of operations such as add, remove, replace and test.

Which method?

Answers

Status codes and headers

The codes worth knowing

CodeMeansThe client should
200 OKWorked, body attachedUse it
201 CreatedMade something newRead Location
202 AcceptedWill be done laterFollow the status URL
204 No ContentWorked, no bodyGo on
304 Not ModifiedYour copy is still goodUse the copy
400 Bad RequestThe request is malformedFix it, do not retry
401 UnauthorizedNo valid credentialsSign in or refresh, then retry once
403 ForbiddenKnown, but not allowedStop
404 Not FoundNo such resource, or you may not know of itStop
405 Method Not AllowedWrong handle for this doorRead Allow
409 ConflictClashes with the current stateReload and decide
412 Precondition FailedThe version you named is oldReload and retry
422 Unprocessable ContentWell formed, but breaks a ruleFix the fields
429 Too Many RequestsOver the limitWait for Retry-After
500 Internal Server ErrorA fault on our sideRetry only if idempotent
503 Service UnavailableOverloaded or in maintenanceWait, with backoff
2xx worked, 3xx look elsewhere or use your copy, 4xx the caller must change something, 5xx the server failed.

Five headers that do most of the work

HeaderSaysExample
Content-TypeThe format of this bodyapplication/json
AcceptThe formats I can readapplication/json
AuthorizationWho I amBearer and a token
Cache-ControlWho may keep this, for how longmax-age=3600
ETagThe 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
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 @"] }}
Problem Details, RFC 9457. Extra members such as errors are allowed. More in API error handling.

Error design has its own page: API error handling.

The path

One request, end to end

A stateless API behind shared HTTP parts

A client outside our system sends requests to a CDN, also outside, which keeps public GET answers. Inside our system a load balancer and gateway check the token and the rate limit and call one of two identical server machines without sessions. Both servers use the same shared stores: Redis as a cache and PostgreSQL as the database.
Either API server can answer, because no session lives in them, and both use both stores (one line each is drawn). Public reads often stop at the CDN.
  1. 1

    The client sends a request

    Method, URL, headers such as Authorization and Content-Type, and sometimes a body.

  2. 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. 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. 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. 5

    The server uses the database

    Through a connection pool, with a transaction for a write.

  6. 6

    The answer goes back

    Status code, caching headers and a body.

A read that costs almost nothing

The second answer carries no body. Headers, checks and shared caches are explained in API caching.

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

0.8×0.3 KB+0.2×20 KB=4.24 KBinstead of20 KB0.8 \times 0.3\,\text{KB} + 0.2 \times 20\,\text{KB} = 4.24\,\text{KB} \quad\text{instead of}\quad 20\,\text{KB}
An assumed 20 KB answer, 0.3 KB for a 304, and 80% of polls finding nothing new: 79% fewer bytes. The request itself still happens.

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

Check the version and write in one database statement: update where id and version both match. To refuse writes without If-Match, answer 428 Precondition Required.

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.

JSON
{  "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"  }}
Page numbers suit small lists. For long or busy lists, leave out the total and return a cursor. The Link header (RFC 8288) can carry the same links.

Cost of a full walk

requests=⌈Nlimit⌉=⌈2350100⌉=24\text{requests} = \left\lceil \frac{N}{\text{limit}} \right\rceil = \left\lceil \frac{2350}{100} \right\rceil = 24
At 5,000 requests an hour, one client can do about 208 such walks an hour. Offer an export if people need all of it.

Maturity

How much REST is enough?

Leonard Richardson's model, described by Martin Fowler, has four levels. Most public APIs stop at level 2.

LevelYou haveYou gain
0One URL, everything is a POSTA tunnel through HTTP
1Many resourcesAddresses
2Methods and status codesCaching, safe retries, general tools
3Links in answers (HATEOAS)Clients follow links instead of building URLs
JSON
{  "id": 9, "seat": 12, "state": "BOOKED",  "_links": {    "self":     { "href": "/bookings/9" },    "check-in": { "href": "/bookings/9/check-in" },    "cancel":   { "href": "/bookings/9" }  }}
When the state becomes CANCELLED, the check-in link disappears. The client shows a button only if its link is there.

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

Deprecation is RFC 9745 and Sunset is RFC 8594. Where the version goes is covered in API versioning.

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

Python
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]
FastAPI checks the body against the model, answers 422 when it does not fit, and serves an OpenAPI description at /openapi.json.
Python
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 way
requests has no timeout unless you give one.

Operate

Running it in production

WatchBecauseDo
Rate, errors and p99 per routeAn average hides one slow routeGroup by route template, not by raw URL
4xx by codeA jump in 401 or 422 is often a client releaseAlert on change, not on zero
429 and Retry-AfterClients must slow downPublish the limits
Request and body sizeOne huge body can fill memorySet limits at the gateway
Cache hit ratioA new query parameter can end all hitsNormalise the key
Calls to deprecated routesYou cannot remove what is still usedCount 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

RESTGraphQLgRPCWebSockets
AddressMany URLsOne endpointService methodsOne open connection
Shape of the answerServer decidesClient decidesSchema decidesYou decide
FormatOften JSONUsually JSONProtobuf by defaultAny message
HTTP cachingBuilt inNeeds GET and hashed queriesNot usedNone
Server pushNoSubscriptionsStreamsYes, both ways
From a browserDirectlyDirectlygRPC-Web, usually with a proxyDirectly
Good forPublic APIs, CRUDScreens with varied needsCalls between servicesChat, live updates
REST is not tied to HTTP/1.1 or JSON, and connections are reused by default. The full comparison is in REST, GraphQL and gRPC.

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.

Sources