TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท web ยท apis ยท http ยท spring

REST API design

Designing HTTP APIs around resources, with nouns in URLs, standard methods used for their real semantics, honest status codes, stateless requests, paged lists, standard error bodies and conditional requests for caching and safe updates.

16 min6 animations

๐Ÿ“š Builds on๐Ÿ“ฎ HTTP

๐Ÿ–จ๏ธ Cheat sheet

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:

URLWhat it names
/productsthe collection of products
/products/42one product, by id
/products/42/reviewsa sub-collection that only makes sense under its parent
/getProduct?id=42, /createOrderavoid: 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:

StrategyExampleTrade-off
Path/v2/productsobvious and easy to route and cache; the version leaks into every URL
Header or media typeAccept: application/vnd.shop.v2+jsonURLs stay stable; harder to try in a browser, and caches must Vary on the header
Query parameter/products?version=2simple, 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.

๐Ÿ”ง Going deeper

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.

Resources and URLs5 steps
๐Ÿฌ SupermarketDairy aisle0123Card under spot 420123๐Ÿง‘Shopper
Press play and watch it happen!

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

MethodUseSafeIdempotent
GETread a resource or collectionyesyes
POSTcreate in a collection (server picks the id), or run a non-CRUD actionnono
PUTreplace the resource at this URL with the body (or create it at a client-chosen URL)noyes
PATCHpartial updatenonot guaranteed
DELETEremove the resourcenoyes

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.

Methods and their semantics6 steps
๐Ÿง‘Shopper๐Ÿ›Ž๏ธOrder desk
Press play and watch it happen!

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

CodeUse it when
200 OKa read or update succeeded and there's a body
201 Createda POST (or PUT) created a resource; include a Location header with its URL, and usually the representation
204 No Contentsuccess with no body, typical for DELETE
400 Bad Requestthe request can't be parsed or is malformed: broken JSON, wrong types, missing required parameter
401 / 403not authenticated / authenticated but not allowed
404 Not Foundno resource at this URL (also used to avoid revealing that a resource exists)
409 Conflictthe request conflicts with the resource's current state: cancelling a shipped order, a duplicate unique key
412 Precondition Faileda conditional header such as If-Match didn't hold (see below)
422 Unprocessable Contentwell-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.

Status codes chosen well5 steps
๐Ÿง‘Shopper๐Ÿ›Ž๏ธOrder desk๐Ÿ“ฆ Stock room
Press play and watch it happen!

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=20Cursor: ?after=eyJpZCI6NDJ9&limit=20
Jump to page Nyesno, only next (and sometimes previous)
Rows inserted or deleted while pagingitems repeat or get skippedstable: continues after the last item seen
Cost on deep pagesthe database still walks past offset rowsan index seek on the sort key: WHERE (price, id) > (?, ?)
Total counteasy to addoften 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.

Paging through a list4 steps
๐Ÿง‘Shopper๐Ÿ›Ž๏ธDesk 1๐Ÿ›Ž๏ธDesk 2๐Ÿ“‹ Stock list๐Ÿง‘โ€๐Ÿ”งStock clerk
Press play and watch it happen!

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: GET with If-None-Match: "v3". If the current ETag still matches, the server answers 304 Not Modified with no body. The same mechanism as browser caching in HTTP.
  • Optimistic concurrency: PUT or PATCH with If-Match: "v3". The server applies the change only if the current ETag is still "v3", otherwise it answers 412 Precondition Failed and changes nothing. This prevents the lost update, where the second writer silently overwrites the first. An API can insist on the header and answer 428 Precondition Required when 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.

ETags and conditional requests5 steps
๐Ÿ‘ฉAna๐Ÿ‘จBen๐Ÿ›Ž๏ธPrice desk๐Ÿท๏ธ Shelf tag 42
Press play and watch it happen!

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 {4    private final OrderService orders;5    OrderController(OrderService orders) { this.orders = orders; }6 7    @GetMapping("/{id}")8    ResponseEntity<OrderDto> get(@PathVariable long id) {9        Order order = orders.find(id);                       // throws OrderNotFound10        return ResponseEntity.ok().eTag(String.valueOf(order.version())).body(OrderDto.of(order));11    }12 13    @PostMapping14    ResponseEntity<OrderDto> create(@Valid @RequestBody NewOrder body) {15        Order order = orders.create(body);16        URI location = ServletUriComponentsBuilder.fromCurrentRequest()17                .path("/{id}").buildAndExpand(order.id()).toUri();18        return ResponseEntity.created(location).body(OrderDto.of(order));   // 201 + Location19    }20 21    @DeleteMapping("/{id}")22    ResponseEntity<Void> delete(@PathVariable long id) {23        orders.delete(id);24        return 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 exceptions3 4    @ExceptionHandler(OrderNotFound.class)5    ProblemDetail notFound(OrderNotFound e) {6        ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage());7        pd.setType(URI.create("https://api.shop.example/problems/order-not-found"));8        pd.setTitle("Order not found");9        return pd;10    }11 12    @ExceptionHandler(OrderAlreadyShipped.class)13    ProblemDetail conflict(OrderAlreadyShipped e) {14        return 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.

A REST controller in Spring4 steps
๐Ÿง‘Shopper๐Ÿง‘โ€๐Ÿ’ผDesk clerk๐Ÿ“Complaints desk๐Ÿ“ฆ Stock room
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 4 questions about REST API design, told the same way as the story.
  1. A shopper hands in the same order list twice because no receipt came back. What happens, and what stops it?
  2. Bag 7 already left in the van, and the shopper asks to cancel it. Which receipt fits?
  3. Ana and Ben both read sticker 3. Ana changes the price first. Ben then asks for a change, only if it's still sticker 3. What happens?
  4. While a shopper pages through the fruit, a cheaper fruit is added at the top. Which way of asking for the next page still works?
Answer every question to check.Passing marks REST API design as done.
Got the hang of REST API design? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ”Œ Designing APIsStep 2 of 5

โ† Previous on the path๐Ÿ“ฎ HTTPNext on the path โ†’๐Ÿฑ GraphQL

๐Ÿ‘‰ Read next

  • ๐ŸฑGraphQLOrdering a custom bento box on one form: tick exactly what you want, and kitchen stations fill each compartment.