Aisles and shelf labels
Think of a big, well-organised supermarket. Every aisle has a sign: Fruit, Dairy, Bread. Every spot on a shelf has a small label with a number. If you know the label, "Dairy, spot 42", you can walk straight to the milk.
The things the shop looks after (products, orders, shoppers) are called resources. Each one has its own label, and the labels are always names of things, never instructions. There's no sign that says "go and get milk". There's a sign that says "Dairy", and you decide what to do there.
Some things live inside others: the tasting notes for the milk sit on a little card under spot 42. That's handy, but a good shop doesn't hide things five levels deep. One step in is usually enough.
Now and then the shop changes its layout. A careful shop doesn't swap all the signs overnight. It puts up the new "Layout 2" signs and keeps the old ones working for a while, so regular shoppers don't get lost.
Resources and URLs
REST models an API as resources addressed by URLs, and manipulated through the standard methods of HTTP. Good URLs are nouns, and the method carries the verb:
| URL | What it names |
|---|---|
/products | the collection of products |
/products/42 | one product, by id |
/products/42/reviews | a sub-collection that only makes sense under its parent |
/getProduct?id=42, /createOrder | avoid: verbs belong in the method |
Use plural collection names, stable ids (not database row positions that change), and nest one level when the
child truly belongs to the parent. Deeper paths like /customers/7/orders/3/lines/2 couple clients to your
hierarchy; once a resource has its own id, give it a top-level URL (/order-lines/2) and filter by parent instead.
Versioning. URLs and response shapes are a contract. Additive changes (a new optional field, a new endpoint) are safe if clients ignore unknown fields. For breaking changes the common strategies are:
| Strategy | Example | Trade-off |
|---|---|---|
| Path | /v2/products | obvious and easy to route and cache; the version leaks into every URL |
| Header or media type | Accept: application/vnd.shop.v2+json | URLs stay stable; harder to try in a browser, and caches must Vary on the header |
| Query parameter | /products?version=2 | simple, but easy to forget and mixes with filters |
Whatever you pick, run the old version alongside the new one for a published period before retiring it.
REST isn't the only style: GraphQL suits clients that need to shape one response from many resources, and gRPC suits internal service-to-service calls with strict, generated contracts.
Links in responses (HATEOAS)
Fielding's REST also includes hypermedia as the engine of application state: responses carry links to related
resources and allowed next actions ("payment": "/orders/7/payment"), so a client could navigate without hardcoding
URLs. Formats like HAL and libraries like Spring HATEOAS support this. In practice most JSON APIs called "REST" don't
do it: clients are written against documented URLs, often from an OpenAPI description. Links are still useful for
pagination (next) and for pointing to a newly created resource, but strict hypermedia-driven clients are rare.
The same few things, anywhere in the shop
Take the order desk, where the shop packs bags from the stock room for people who order ahead. In every part of the shop you can do the same few things: look, add, replace, change a bit, or remove. These actions are called methods.
Looking never changes anything, so you can look as often as you like. Replacing is safe to repeat too: hand in "this bag should hold bread and jam" twice, and you still get one bag with bread and jam. Removing twice still leaves the bag gone. Changing a bit depends on how you ask: "make it two loaves" is safe to repeat, but "add one more loaf" adds another loaf each time.
Adding is different. Hand in the same list twice and the shop packs two bags. So when you're not sure the first one got through, you write a ticket number at the top of your list. If the same number turns up again, the desk knows it already packed that bag and just hands you the same receipt.
Methods and their semantics
| Method | Use | Safe | Idempotent |
|---|---|---|---|
GET | read a resource or collection | yes | yes |
POST | create in a collection (server picks the id), or run a non-CRUD action | no | no |
PUT | replace the resource at this URL with the body (or create it at a client-chosen URL) | no | yes |
PATCH | partial update | no | not guaranteed |
DELETE | remove the resource | no | yes |
Safe means the client isn't asking for a state change, so crawlers, prefetchers and caches may call it freely.
Idempotent means N identical requests have the same intended effect on the server as one, so clients and proxies may
retry after a lost response. It's about the effect, not the response: the second DELETE may return 404 where the
first returned 204, and the resource is still gone either way.
PATCH depends on the patch document: a JSON Merge Patch that sets "status": "paid" is effectively idempotent,
while a JSON Patch add to an array is not. Never make a GET change state.
Idempotency keys for POST. Because a retried POST creates a duplicate, APIs that take payments or orders accept a
client-generated key (commonly an Idempotency-Key header, which is an IETF draft rather than a finished standard).
The server stores the key with the result and replays the stored response for a repeat. See
idempotency for how to store keys safely.
Receipts with clear codes
Every visit ends with a receipt, and the receipt has a code at the top. A good shop picks the code carefully, so you know exactly what happened without asking. That code is the status code.
- "Created, and here's where to find it": your new bag is on the shelf, and the receipt says which spot.
- "Done, nothing to hand back": you asked to remove something, and it's gone.
- "I can't read your list": the writing is a scribble.
- "I can read it, but it makes no sense": you asked for minus three apples.
- "There's nothing at that spot."
- "That clashes with how things are now": you tried to cancel a bag that already left in the van.
When something goes wrong, a good shop also staples a complaint slip to the receipt, always laid out the same way: what kind of problem, a short title, the code, and a sentence about your case. Shoppers learn to read one slip and can then read them all.
Status codes chosen well
| Code | Use it when |
|---|---|
200 OK | a read or update succeeded and there's a body |
201 Created | a POST (or PUT) created a resource; include a Location header with its URL, and usually the representation |
204 No Content | success with no body, typical for DELETE |
400 Bad Request | the request can't be parsed or is malformed: broken JSON, wrong types, missing required parameter |
401 / 403 | not authenticated / authenticated but not allowed |
404 Not Found | no resource at this URL (also used to avoid revealing that a resource exists) |
409 Conflict | the request conflicts with the resource's current state: cancelling a shipped order, a duplicate unique key |
412 Precondition Failed | a conditional header such as If-Match didn't hold (see below) |
422 Unprocessable Content | well-formed and understood, but semantically invalid: quantity -3 |
The 400 versus 422 line is a convention: many APIs (and Spring's default for bean validation) use 400 for all
invalid input. Pick one rule and apply it everywhere. Don't return 200 with an error inside the body; clients,
proxies, retries and monitoring all rely on the code.
Error bodies. RFC 9457 (which replaced RFC 7807) defines problem details, a standard JSON error format
served as application/problem+json, with the members type (a URI identifying the problem type), title,
status, detail and instance, plus any extension members you need:
1{2"type": "https://api.shop.example/problems/invalid-quantity",3"title": "Invalid quantity",4"status": 422,5"detail": "Quantity must be at least 1, got -3.",6"instance": "/orders",7"errors": [{ "field": "lines[0].quantity", "message": "must be at least 1" }]8}
Keep type stable so clients can branch on it, and never leak stack traces in detail.
One page at a time, and no memory of you
The staff don't remember you between visits. Each time you come to a desk, you show your loyalty card and say everything they need. That sounds tiring, but it means any desk in the shop can help you, and a new desk can open on a busy day without being told who you are.
Ask the service desk for "all the fruit, cheapest first" and you won't get a list as long as the shop. You get one page, three items long, and a slip at the bottom: "carry on after the pears". This is called pagination. Next time, you hand in the slip, at any desk, and get the next three.
There's another way: "skip the first three". It's simpler, but if someone puts a new cheap fruit at the top of the list while you're reading, everything moves down one, and you see the pears twice. The "carry on after the pears" slip doesn't have that problem.
Statelessness, pagination, filtering and sorting
Stateless means each request carries everything the server needs to handle it: credentials (a bearer token), the resource, and any position in a list. The server keeps no per-client session between requests, so any instance behind a load balancer can serve any request, and instances can be added or replaced freely. Application data still lives in the database; what's missing is conversation state.
Filtering and sorting use query parameters on the collection:
GET /products?category=fruit&sort=price&limit=3. Whitelist the sortable and filterable fields and index them, and
give the sort a unique tiebreaker (price,id) so the order is deterministic.
Pagination keeps responses bounded. Two common styles:
Offset: ?offset=40&limit=20 | Cursor: ?after=eyJpZCI6NDJ9&limit=20 | |
|---|---|---|
| Jump to page N | yes | no, only next (and sometimes previous) |
| Rows inserted or deleted while paging | items repeat or get skipped | stable: continues after the last item seen |
| Cost on deep pages | the database still walks past offset rows | an index seek on the sort key: WHERE (price, id) > (?, ?) |
| Total count | easy to add | often omitted, since counting is expensive |
A cursor is an opaque token (often the base64 of the last item's sort key) returned with each page, in the body or
in a Link: <...>; rel="next" header. Clients must treat it as opaque, so you can change its contents later.
Price-tag stickers
Every shelf tag has a small sticker with a number on it, and the shop puts on a new sticker every time anything on the tag changes. That sticker is called an ETag.
It helps in two ways. If you already have a photo of the tag with sticker 3, you can ask "still sticker 3?", and the shop just says "yes, nothing new" instead of telling you everything again.
It also stops two staff members from undoing each other's work. Ana and Ben both read the tag with sticker 3. Ana changes the price first, and the tag gets sticker 4. Then Ben tries to change it, saying "only if it's still sticker 3". It isn't, so the price desk refuses, and Ben looks again before deciding what to do. Nobody's change is lost without anyone noticing.
ETags and conditional requests
A server can send an ETag header, an opaque version identifier for the current representation (a hash, or a
version column). Clients send it back in conditional headers:
- Caching:
GETwithIf-None-Match: "v3". If the current ETag still matches, the server answers304 Not Modifiedwith no body. The same mechanism as browser caching in HTTP. - Optimistic concurrency:
PUTorPATCHwithIf-Match: "v3". The server applies the change only if the current ETag is still"v3", otherwise it answers412 Precondition Failedand changes nothing. This prevents the lost update, where the second writer silently overwrites the first. An API can insist on the header and answer428 Precondition Requiredwhen it's missing.
The check and the write must be atomic on the server, typically
UPDATE products SET price = ?, version = version + 1 WHERE id = ? AND version = ?, and treat zero updated rows as
the 412. Weak ETags (W/"v3") mean "semantically equivalent", and If-Match requires a strong comparison, so use
strong ETags for concurrency control.
Behind the desk
Behind each desk, a clerk, called the controller, takes the lists and writes the receipts. They don't do everything themselves: they fetch from the stock room, and when something goes wrong they pass the problem to the complaints desk, which fills in the same tidy complaint slip every time.
That way every desk gives the same kind of receipt for the same kind of problem, and nobody writes their own messy note.
In Spring
A @RestController maps methods and paths to handler methods. ResponseEntity controls the status and headers, so
201 with Location and 204 are one line each:
1@RestController2@RequestMapping("/orders")3class OrderController {4private final OrderService orders;5OrderController(OrderService orders) { this.orders = orders; }67@GetMapping("/{id}")8ResponseEntity<OrderDto> get(@PathVariable long id) {9Order order = orders.find(id); // throws OrderNotFound10return ResponseEntity.ok().eTag(String.valueOf(order.version())).body(OrderDto.of(order));11}1213@PostMapping14ResponseEntity<OrderDto> create(@Valid @RequestBody NewOrder body) {15Order order = orders.create(body);16URI location = ServletUriComponentsBuilder.fromCurrentRequest()17.path("/{id}").buildAndExpand(order.id()).toUri();18return ResponseEntity.created(location).body(OrderDto.of(order)); // 201 + Location19}2021@DeleteMapping("/{id}")22ResponseEntity<Void> delete(@PathVariable long id) {23orders.delete(id);24return ResponseEntity.noContent().build(); // 20425}26}
Errors go in one place, a @RestControllerAdvice. Spring's ProblemDetail class is the RFC 9457 body; returning
it from an @ExceptionHandler sets the status and the application/problem+json content type:
1@RestControllerAdvice2class ApiErrors extends ResponseEntityExceptionHandler { // problem details for Spring MVC's own exceptions34@ExceptionHandler(OrderNotFound.class)5ProblemDetail notFound(OrderNotFound e) {6ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());7pd.setType(URI.create("https://api.shop.example/problems/order-not-found"));8pd.setTitle("Order not found");9return pd;10}1112@ExceptionHandler(OrderAlreadyShipped.class)13ProblemDetail conflict(OrderAlreadyShipped e) {14return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, e.getMessage());15}16}
Extending ResponseEntityExceptionHandler makes Spring MVC's built-in exceptions (a @Valid failure, an unreadable
body, an unsupported method) render as problem details too. Alternatively, in Spring Boot, spring.mvc.problemdetails.enabled=true
registers such a handler for you if you don't write your own. A failed @Valid on a request body is a MethodArgumentNotValidException, which
maps to 400 by default; override handleMethodArgumentNotValid in the advice if your rule is 422.