Part 03 · The Language of the Web
REST and Resource Modeling
Thinking in resources instead of actions, and designing URLs a client can guess.
⏱ 1-2 hours · Station 36 of 153
Forty endpoints and nobody can guess the forty-first
A team's API grew one feature at a time. Two years later it has /getUserById, /fetchUserOrders, /createNewOrder, /order/cancel, /cancelOrderItem, /updateUserEmailAddress and thirty more. Every new frontend developer asks the same questions: is it get or fetch? /order or /orders? POST or GET for cancel? Each endpoint returns errors in its own shape. Nobody can guess an URL; they have to look it up.
Now look at an API designed around things instead of actions:
GET /users/42 one user
GET /users/42/orders that user's orders
POST /orders create an order
PATCH /orders/7 change part of order 7
DELETE /orders/7/items/3 remove one item
Once you've seen three of these, you can guess the rest. That's the core idea of REST: name your data as resources with URLs, and use the standard HTTP methods (lesson 4) and status codes (lesson 5) to act on them. It's not a library or a protocol; it's a way of designing APIs so they're predictable for clients, caches and new team members.
The problem: every action invents its own rules
| Question a client has | Action-style API (RPC over HTTP) | Resource-style API (REST) |
|---|---|---|
| What's the URL? | Look it up for every action | Guess from the noun: /orders/7 |
| Which method? | Often POST for everything | GET reads, POST creates, PATCH/PUT updates, DELETE removes |
| Did it work? | 200 {"success": false} sometimes | Status code: 201, 404, 409, 422... |
| Can a cache or proxy help? | No idea what's safe | GET is safe and cacheable by definition |
| Is retrying safe? | Depends, read the docs | PUT and DELETE are idempotent (next lesson) |
The more an API reuses what HTTP already defines, the less every client has to learn, and the more the existing machinery (browsers, caches, proxies, retry libraries) can do for free.
Think of a library
In a library you don't walk to a "fetch-a-book-about-history desk" or a "return-a-borrowed-novel window". Things have addresses: shelf 7, row 3, book 12. And there are a few standard actions you can take on anything with an address: look at it, borrow it, return it, report it damaged.
- The address is the URL:
/shelves/7/books/12. - The standard actions are the HTTP methods: GET, POST, PUT, PATCH, DELETE.
- New books don't need new desks; they just get new addresses.
Where the analogy stops working. A library book is one physical object. A REST resource is a representation of data that may live in several tables, be computed on the fly, or come back as JSON for one client and CSV for another. The URL names the thing, not the storage.
The building blocks
- Resources are nouns. Users, orders, invoices, reviews. Even processes can be resources: a password reset is
POST /password-resets, a payment attempt isPOST /payments. - Collections and items.
/ordersis the collection,/orders/7is one item in it. Use plural nouns consistently. - Methods carry the verb.
GET /orderslists,POST /orderscreates,GET /orders/7reads,PUT /orders/7replaces,PATCH /orders/7changes some fields,DELETE /orders/7removes. The URL never saysget,createordelete. - Nesting shows ownership, a level or two deep.
/books/2/reviewsreads naturally: the reviews of book 2. Deeper chains like/users/1/orders/7/items/3/notesget brittle. Once a child has its own id, it can live at its own top-level URL too (/items/3). - Status codes tell the outcome.
201 Createdwith aLocationheader pointing at the new resource,204 No Contentafter a delete,404when the resource doesn't exist,405 Method Not Allowedwith anAllowheader when the method doesn't apply,409for conflicts,422for invalid data. - Representations, not tables. The JSON you return is a view designed for clients. Don't leak column names, internal flags or join tables just because the database has them.
- Statelessness. Each request carries everything needed to handle it (auth token, ids, parameters). The server doesn't remember "the current order" between requests (Module 1, lesson 5). This is what lets any server behind a load balancer handle any request.
- Not everything fits, and that's fine. "Send this invoice by email" is an action. Common patterns: model it as a resource (
POST /invoices/7/emails) or allow a clearly named action sub-path (POST /invoices/7:sendor/invoices/7/send). Be consistent, and pick one style per API.
Which of these is the most RESTful way to cancel order 7, given that a cancelled order still exists and can be viewed later?
Behind the scenes: creating a review
POST /books/2/reviews, from route to response
Step 1/5 The request names a resource
POST /books/2/reviews with body {"stars":5}. The URL says which collection; the method says create something in it.
- method
- POST
- collection
- /books/2/reviews
The picture to keep in your head
A REST API is a map of addresses plus a small, fixed set of verbs.
- Addresses (URLs) name things: collections and items, nested where ownership is real.
- Verbs (methods) are the same everywhere: GET, POST, PUT, PATCH, DELETE.
- Answers (status codes) are the same everywhere: 200, 201, 204, 404, 405, 409, 422.
- Learn one resource and you can guess the next. That's the test of a good design.
Try it: is this a good resource design?
Good URL or action URL?
the orders of user 42
Code from first principles
A tiny REST engine with no web framework: it splits the path into segments, treats an odd number as a collection and an even number as one item, checks that parents exist, and picks the action from the method. There are no verbs in any URL. Request bodies arrive already decoded (decoding JSON was lesson 7).
package main
import (
"fmt"
"strconv"
"strings"
)
// A field is a name and its value already written as JSON ("\"Dune\"" or "5").
type field struct{ k, v string }
type record struct {
id int
fields []field
}
// Every collection lives at its own path: "/books", "/books/2/reviews", ...
var store = map[string][]*record{}
var nextID = map[string]int{}
// children says which collections may hang under which: a book has reviews.
var children = map[string]string{"": "books", "books": "reviews"}
func obj(id int, fs []field) string {
parts := []string{}
if id > 0 {
parts = append(parts, `"id":`+strconv.Itoa(id))
}
for _, f := range fs {
parts = append(parts, `"`+f.k+`":`+f.v)
}
return "{" + strings.Join(parts, ",") + "}"
}
func find(coll string, id int) *record {
for _, r := range store[coll] {
if r.id == id {
return r
}
}
return nil
}
func notFound(p string) string { return `404, {"error":"not found: ` + p + `"}` }
// handle maps (method, resource path) to an action. Odd number of segments = a collection,
// even = one item in it. Nothing in the URL is a verb; the method says what to do.
func handle(method, path string, body []field) string {
segs := strings.Split(strings.Trim(path, "/"), "/")
parent := ""
for i := 0; i < len(segs); i += 2 { // walk /books/2/reviews/1 pair by pair
if children[parent] != segs[i] {
return notFound("/" + strings.Join(segs[:i+1], "/"))
}
if i+1 < len(segs) && i+2 < len(segs) { // an id in the middle must exist
id, err := strconv.Atoi(segs[i+1])
coll := "/" + strings.Join(segs[:i+1], "/")
if err != nil || find(coll, id) == nil {
return notFound(coll + "/" + segs[i+1])
}
}
parent = segs[i]
}
if len(segs)%2 == 1 { // a collection
coll := "/" + strings.Join(segs, "/")
switch method {
case "GET":
items := []string{}
for _, r := range store[coll] {
items = append(items, obj(r.id, r.fields))
}
return "200, [" + strings.Join(items, ",") + "]"
case "POST":
nextID[coll]++
r := &record{nextID[coll], body}
store[coll] = append(store[coll], r)
return fmt.Sprintf("201, Location: %s/%d, %s", coll, r.id, obj(r.id, r.fields))
}
return "405, Allow: GET, POST"
}
coll := "/" + strings.Join(segs[:len(segs)-1], "/")
id, err := strconv.Atoi(segs[len(segs)-1])
r := find(coll, id)
if err != nil || r == nil {
return notFound(path)
}
switch method {
case "GET":
return "200, " + obj(r.id, r.fields)
case "PATCH": // change only the fields that were sent
for _, nf := range body {
for i := range r.fields {
if r.fields[i].k == nf.k {
r.fields[i].v = nf.v
}
}
}
return "200, " + obj(r.id, r.fields)
case "DELETE":
list := store[coll][:0]
for _, x := range store[coll] {
if x.id != id {
list = append(list, x)
}
}
store[coll] = list
delete(store, path+"/reviews") // its children go with it
return "204"
}
return "405, Allow: GET, PATCH, DELETE"
}
func main() {
reqs := []struct {
method, path string
body []field
}{
{"POST", "/books", []field{{"title", `"Dune"`}}},
{"POST", "/books", []field{{"title", `"Emma"`}}},
{"GET", "/books", nil},
{"GET", "/books/2", nil},
{"POST", "/books/2/reviews", []field{{"stars", "5"}}},
{"GET", "/books/2/reviews", nil},
{"PATCH", "/books/1", []field{{"title", `"Dune Messiah"`}}},
{"DELETE", "/books/1", nil},
{"GET", "/books/1", nil},
{"POST", "/books/9/reviews", []field{{"stars", "1"}}},
{"PUT", "/books", nil},
{"GET", "/authors", nil},
}
for _, q := range reqs {
label := q.method + " " + q.path
if q.body != nil {
label += " " + obj(0, q.body)
}
fmt.Printf("%-40s -> %s\n", label, handle(q.method, q.path, q.body))
}
}// A field is [name, value already written as JSON] ('"Dune"' or "5").
// Every collection lives at its own path: "/books", "/books/2/reviews", ...
const store = new Map();
const nextID = new Map();
// children says which collections may hang under which: a book has reviews.
const children = { "": "books", books: "reviews" };
function obj(id, fs) {
const parts = [];
if (id > 0) parts.push(`"id":${id}`);
for (const [k, v] of fs) parts.push(`"${k}":${v}`);
return "{" + parts.join(",") + "}";
}
const find = (coll, id) => (store.get(coll) || []).find((r) => r.id === id);
const notFound = (p) => `404, {"error":"not found: ${p}"}`;
const toId = (s) => (/^\d+$/.test(s) ? Number(s) : NaN);
// handle maps (method, resource path) to an action. Odd number of segments = a collection,
// even = one item in it. Nothing in the URL is a verb; the method says what to do.
function handle(method, path, body) {
const segs = path.replace(/^\/|\/$/g, "").split("/");
let parent = "";
for (let i = 0; i < segs.length; i += 2) { // walk /books/2/reviews/1 pair by pair
if (children[parent] !== segs[i]) return notFound("/" + segs.slice(0, i + 1).join("/"));
if (i + 2 < segs.length) { // an id in the middle must exist
const coll = "/" + segs.slice(0, i + 1).join("/");
if (!find(coll, toId(segs[i + 1]))) return notFound(coll + "/" + segs[i + 1]);
}
parent = segs[i];
}
if (segs.length % 2 === 1) { // a collection
const coll = "/" + segs.join("/");
if (method === "GET") return "200, [" + (store.get(coll) || []).map((r) => obj(r.id, r.fields)).join(",") + "]";
if (method === "POST") {
nextID.set(coll, (nextID.get(coll) || 0) + 1);
const r = { id: nextID.get(coll), fields: body };
store.set(coll, [...(store.get(coll) || []), r]);
return `201, Location: ${coll}/${r.id}, ${obj(r.id, r.fields)}`;
}
return "405, Allow: GET, POST";
}
const coll = "/" + segs.slice(0, -1).join("/");
const id = toId(segs.at(-1));
const r = find(coll, id);
if (!r) return notFound(path);
if (method === "GET") return "200, " + obj(r.id, r.fields);
if (method === "PATCH") { // change only the fields that were sent
for (const [k, v] of body) for (const f of r.fields) if (f[0] === k) f[1] = v;
return "200, " + obj(r.id, r.fields);
}
if (method === "DELETE") {
store.set(coll, store.get(coll).filter((x) => x.id !== id));
store.delete(path + "/reviews"); // its children go with it
return "204";
}
return "405, Allow: GET, PATCH, DELETE";
}
const reqs = [
["POST", "/books", [["title", '"Dune"']]],
["POST", "/books", [["title", '"Emma"']]],
["GET", "/books", null],
["GET", "/books/2", null],
["POST", "/books/2/reviews", [["stars", "5"]]],
["GET", "/books/2/reviews", null],
["PATCH", "/books/1", [["title", '"Dune Messiah"']]],
["DELETE", "/books/1", null],
["GET", "/books/1", null],
["POST", "/books/9/reviews", [["stars", "1"]]],
["PUT", "/books", null],
["GET", "/authors", null],
];
for (const [method, path, body] of reqs) {
let label = method + " " + path;
if (body) label += " " + obj(0, body);
console.log(`${label.padEnd(40)} -> ${handle(method, path, body)}`);
}use std::collections::HashMap;
// A field is a name and its value already written as JSON ("\"Dune\"" or "5").
type Field = (String, String);
struct Record {
id: u32,
fields: Vec<Field>,
}
struct Api {
// Every collection lives at its own path: "/books", "/books/2/reviews", ...
store: HashMap<String, Vec<Record>>,
next_id: HashMap<String, u32>,
}
// children says which collections may hang under which: a book has reviews.
fn child_of(parent: &str) -> &str {
match parent {
"" => "books",
"books" => "reviews",
_ => "",
}
}
fn obj(id: u32, fs: &[Field]) -> String {
let mut parts = Vec::new();
if id > 0 {
parts.push(format!("\"id\":{}", id));
}
for (k, v) in fs {
parts.push(format!("\"{}\":{}", k, v));
}
format!("{{{}}}", parts.join(","))
}
fn not_found(p: &str) -> String {
format!("404, {{\"error\":\"not found: {}\"}}", p)
}
impl Api {
fn exists(&self, coll: &str, id: Option<u32>) -> bool {
match (self.store.get(coll), id) {
(Some(list), Some(id)) => list.iter().any(|r| r.id == id),
_ => false,
}
}
// handle maps (method, resource path) to an action. Odd number of segments = a collection,
// even = one item in it. Nothing in the URL is a verb; the method says what to do.
fn handle(&mut self, method: &str, path: &str, body: Option<&[Field]>) -> String {
let segs: Vec<&str> = path.trim_matches('/').split('/').collect();
let mut parent = "";
let mut i = 0;
while i < segs.len() {
// walk /books/2/reviews/1 pair by pair
if child_of(parent) != segs[i] {
return not_found(&format!("/{}", segs[..=i].join("/")));
}
if i + 2 < segs.len() {
// an id in the middle must exist
let coll = format!("/{}", segs[..=i].join("/"));
if !self.exists(&coll, segs[i + 1].parse().ok()) {
return not_found(&format!("{}/{}", coll, segs[i + 1]));
}
}
parent = segs[i];
i += 2;
}
if segs.len() % 2 == 1 {
// a collection
let coll = format!("/{}", segs.join("/"));
return match method {
"GET" => {
let items: Vec<String> = self.store.get(&coll).map_or(vec![], |l| l.iter().map(|r| obj(r.id, &r.fields)).collect());
format!("200, [{}]", items.join(","))
}
"POST" => {
let id = self.next_id.entry(coll.clone()).or_insert(0);
*id += 1;
let r = Record { id: *id, fields: body.unwrap().to_vec() };
let out = format!("201, Location: {}/{}, {}", coll, r.id, obj(r.id, &r.fields));
self.store.entry(coll).or_default().push(r);
out
}
_ => "405, Allow: GET, POST".to_string(),
};
}
let coll = format!("/{}", segs[..segs.len() - 1].join("/"));
let id: Option<u32> = segs[segs.len() - 1].parse().ok();
if !self.exists(&coll, id) {
return not_found(path);
}
let id = id.unwrap();
let list = self.store.get_mut(&coll).unwrap();
match method {
"GET" => {
let r = list.iter().find(|r| r.id == id).unwrap();
format!("200, {}", obj(r.id, &r.fields))
}
"PATCH" => {
// change only the fields that were sent
let r = list.iter_mut().find(|r| r.id == id).unwrap();
for (k, v) in body.unwrap() {
for f in r.fields.iter_mut() {
if &f.0 == k {
f.1 = v.clone();
}
}
}
format!("200, {}", obj(r.id, &r.fields))
}
"DELETE" => {
list.retain(|x| x.id != id);
self.store.remove(&format!("{}/reviews", path)); // its children go with it
"204".to_string()
}
_ => "405, Allow: GET, PATCH, DELETE".to_string(),
}
}
}
fn f(k: &str, v: &str) -> Vec<Field> {
vec![(k.to_string(), v.to_string())]
}
fn main() {
let mut api = Api { store: HashMap::new(), next_id: HashMap::new() };
let reqs: Vec<(&str, &str, Option<Vec<Field>>)> = vec![
("POST", "/books", Some(f("title", "\"Dune\""))),
("POST", "/books", Some(f("title", "\"Emma\""))),
("GET", "/books", None),
("GET", "/books/2", None),
("POST", "/books/2/reviews", Some(f("stars", "5"))),
("GET", "/books/2/reviews", None),
("PATCH", "/books/1", Some(f("title", "\"Dune Messiah\""))),
("DELETE", "/books/1", None),
("GET", "/books/1", None),
("POST", "/books/9/reviews", Some(f("stars", "1"))),
("PUT", "/books", None),
("GET", "/authors", None),
];
for (method, path, body) in &reqs {
let mut label = format!("{} {}", method, path);
if let Some(b) = body {
label += &format!(" {}", obj(0, b));
}
println!("{:<40} -> {}", label, api.handle(method, path, body.as_deref()));
}
}# A field is [name, value already written as JSON] ('"Dune"' or "5").
# Every collection lives at its own path: "/books", "/books/2/reviews", ...
store = {}
next_id = {}
# children says which collections may hang under which: a book has reviews.
children = {"": "books", "books": "reviews"}
def obj(id, fs):
parts = [f'"id":{id}'] if id > 0 else []
parts += [f'"{k}":{v}' for k, v in fs]
return "{" + ",".join(parts) + "}"
def find(coll, id):
return next((r for r in store.get(coll, []) if r["id"] == id), None)
def not_found(p):
return f'404, {{"error":"not found: {p}"}}'
def to_id(s):
return int(s) if s.isdigit() else None
def handle(method, path, body):
"""Map (method, resource path) to an action. Odd number of segments = a collection,
even = one item in it. Nothing in the URL is a verb; the method says what to do."""
segs = path.strip("/").split("/")
parent = ""
for i in range(0, len(segs), 2): # walk /books/2/reviews/1 pair by pair
if children.get(parent) != segs[i]:
return not_found("/" + "/".join(segs[: i + 1]))
if i + 2 < len(segs): # an id in the middle must exist
coll = "/" + "/".join(segs[: i + 1])
if find(coll, to_id(segs[i + 1])) is None:
return not_found(coll + "/" + segs[i + 1])
parent = segs[i]
if len(segs) % 2 == 1: # a collection
coll = "/" + "/".join(segs)
if method == "GET":
return "200, [" + ",".join(obj(r["id"], r["fields"]) for r in store.get(coll, [])) + "]"
if method == "POST":
next_id[coll] = next_id.get(coll, 0) + 1
r = {"id": next_id[coll], "fields": body}
store.setdefault(coll, []).append(r)
return f"201, Location: {coll}/{r['id']}, {obj(r['id'], r['fields'])}"
return "405, Allow: GET, POST"
coll = "/" + "/".join(segs[:-1])
id = to_id(segs[-1])
r = find(coll, id)
if r is None:
return not_found(path)
if method == "GET":
return "200, " + obj(r["id"], r["fields"])
if method == "PATCH": # change only the fields that were sent
for k, v in body:
for f in r["fields"]:
if f[0] == k:
f[1] = v
return "200, " + obj(r["id"], r["fields"])
if method == "DELETE":
store[coll] = [x for x in store[coll] if x["id"] != id]
store.pop(path + "/reviews", None) # its children go with it
return "204"
return "405, Allow: GET, PATCH, DELETE"
reqs = [
("POST", "/books", [["title", '"Dune"']]),
("POST", "/books", [["title", '"Emma"']]),
("GET", "/books", None),
("GET", "/books/2", None),
("POST", "/books/2/reviews", [["stars", "5"]]),
("GET", "/books/2/reviews", None),
("PATCH", "/books/1", [["title", '"Dune Messiah"']]),
("DELETE", "/books/1", None),
("GET", "/books/1", None),
("POST", "/books/9/reviews", [["stars", "1"]]),
("PUT", "/books", None),
("GET", "/authors", None),
]
for method, path, body in reqs:
label = f"{method} {path}"
if body is not None:
label += " " + obj(0, body)
print(f"{label:<40} -> {handle(method, path, body)}")import java.util.*;
public class Main {
// A field is {name, value already written as JSON} ("\"Dune\"" or "5").
static class Rec {
int id;
List<String[]> fields;
Rec(int id, List<String[]> fields) { this.id = id; this.fields = fields; }
}
// Every collection lives at its own path: "/books", "/books/2/reviews", ...
static Map<String, List<Rec>> store = new HashMap<>();
static Map<String, Integer> nextId = new HashMap<>();
// children says which collections may hang under which: a book has reviews.
static Map<String, String> children = Map.of("", "books", "books", "reviews");
static String obj(int id, List<String[]> fs) {
List<String> parts = new ArrayList<>();
if (id > 0) parts.add("\"id\":" + id);
for (String[] f : fs) parts.add("\"" + f[0] + "\":" + f[1]);
return "{" + String.join(",", parts) + "}";
}
static Rec find(String coll, String idText) {
if (!idText.matches("\\d+")) return null;
int id = Integer.parseInt(idText);
for (Rec r : store.getOrDefault(coll, List.of())) if (r.id == id) return r;
return null;
}
static String notFound(String p) { return "404, {\"error\":\"not found: " + p + "\"}"; }
static String join(String[] segs, int from, int to) {
return "/" + String.join("/", Arrays.copyOfRange(segs, from, to));
}
// handle maps (method, resource path) to an action. Odd number of segments = a collection,
// even = one item in it. Nothing in the URL is a verb; the method says what to do.
static String handle(String method, String path, List<String[]> body) {
String[] segs = path.replaceAll("^/|/$", "").split("/");
String parent = "";
for (int i = 0; i < segs.length; i += 2) { // walk /books/2/reviews/1 pair by pair
if (!segs[i].equals(children.get(parent))) return notFound(join(segs, 0, i + 1));
if (i + 2 < segs.length) { // an id in the middle must exist
String coll = join(segs, 0, i + 1);
if (find(coll, segs[i + 1]) == null) return notFound(coll + "/" + segs[i + 1]);
}
parent = segs[i];
}
if (segs.length % 2 == 1) { // a collection
String coll = join(segs, 0, segs.length);
if (method.equals("GET")) {
List<String> items = new ArrayList<>();
for (Rec r : store.getOrDefault(coll, List.of())) items.add(obj(r.id, r.fields));
return "200, [" + String.join(",", items) + "]";
}
if (method.equals("POST")) {
int id = nextId.merge(coll, 1, Integer::sum);
Rec r = new Rec(id, body);
store.computeIfAbsent(coll, k -> new ArrayList<>()).add(r);
return "201, Location: " + coll + "/" + id + ", " + obj(id, r.fields);
}
return "405, Allow: GET, POST";
}
String coll = join(segs, 0, segs.length - 1);
Rec r = find(coll, segs[segs.length - 1]);
if (r == null) return notFound(path);
switch (method) {
case "GET":
return "200, " + obj(r.id, r.fields);
case "PATCH": // change only the fields that were sent
for (String[] nf : body) for (String[] f : r.fields) if (f[0].equals(nf[0])) f[1] = nf[1];
return "200, " + obj(r.id, r.fields);
case "DELETE":
store.get(coll).removeIf(x -> x.id == r.id);
store.remove(path + "/reviews"); // its children go with it
return "204";
}
return "405, Allow: GET, PATCH, DELETE";
}
static List<String[]> f(String k, String v) {
List<String[]> l = new ArrayList<>();
l.add(new String[]{k, v});
return l;
}
public static void main(String[] args) {
Object[][] reqs = {
{"POST", "/books", f("title", "\"Dune\"")},
{"POST", "/books", f("title", "\"Emma\"")},
{"GET", "/books", null},
{"GET", "/books/2", null},
{"POST", "/books/2/reviews", f("stars", "5")},
{"GET", "/books/2/reviews", null},
{"PATCH", "/books/1", f("title", "\"Dune Messiah\"")},
{"DELETE", "/books/1", null},
{"GET", "/books/1", null},
{"POST", "/books/9/reviews", f("stars", "1")},
{"PUT", "/books", null},
{"GET", "/authors", null},
};
for (Object[] q : reqs) {
String method = (String) q[0], path = (String) q[1];
@SuppressWarnings("unchecked")
List<String[]> body = (List<String[]>) q[2];
String label = method + " " + path + (body != null ? " " + obj(0, body) : "");
System.out.printf("%-40s -> %s%n", label, handle(method, path, body));
}
}
}Output (the same in all five languages):
POST /books {"title":"Dune"} -> 201, Location: /books/1, {"id":1,"title":"Dune"}
POST /books {"title":"Emma"} -> 201, Location: /books/2, {"id":2,"title":"Emma"}
GET /books -> 200, [{"id":1,"title":"Dune"},{"id":2,"title":"Emma"}]
GET /books/2 -> 200, {"id":2,"title":"Emma"}
POST /books/2/reviews {"stars":5} -> 201, Location: /books/2/reviews/1, {"id":1,"stars":5}
GET /books/2/reviews -> 200, [{"id":1,"stars":5}]
PATCH /books/1 {"title":"Dune Messiah"} -> 200, {"id":1,"title":"Dune Messiah"}
DELETE /books/1 -> 204
GET /books/1 -> 404, {"error":"not found: /books/1"}
POST /books/9/reviews {"stars":1} -> 404, {"error":"not found: /books/9"}
PUT /books -> 405, Allow: GET, POST
GET /authors -> 404, {"error":"not found: /authors"}
Reading the output:
- Creates return
201and aLocation:/books/1,/books/2and then/books/2/reviews/1. The client learns the new URL from the response; it never builds it by guessing ids. - The same two URL shapes do everything:
/booksand/books/2handled list, create, read, change and delete. The nested/books/2/reviewsreused exactly the same code. PATCHchanged only the title and returned the updated representation.DELETEreturned204, and the nextGET /books/1is a404: the resource is gone.- Errors point at what's missing: a review for book 9 fails with
not found: /books/9, the parent, not a confusing "review not found". PUT /booksis405withAllow: GET, POST: the resource exists, the method doesn't apply, and the response says which ones do.
And the same shapes on a real public practice API, jsonplaceholder:
$ B=https://jsonplaceholder.typicode.com
$ for p in /posts/1 /posts/1/comments /users/1/posts /posts/9999; do curl -s -o /dev/null -w "GET $p -> %{http_code}\n" $B$p; done
GET /posts/1 -> 200
GET /posts/1/comments -> 200
GET /users/1/posts -> 200
GET /posts/9999 -> 404
$ curl -s $B/posts/1/comments | jq "length, .[0].postId"
5
1
$ curl -s -X POST $B/posts -H "Content-Type: application/json" -d '{"title":"Dune","userId":1}' -w "\nstatus %{http_code}\n"
{
"title": "Dune",
"userId": 1,
"id": 101
}
status 201
/posts/1/commentsand/users/1/posts: nested collections, exactly like/books/2/reviews. You could guess both URLs without docs./posts/9999is a404: a resource that doesn't exist.- POST to the collection returns
201and the new item with its id (this practice API fakes the save, so it always says 101).
Real engineering
- Write the resource list first. Before any code, list the nouns, their URLs, which methods each supports and what each returns. It's the cheapest point to fix a design.
- Be boringly consistent: plural nouns, lower-case with hyphens (
/password-resets), the same id format, the same field naming (created_atorcreatedAt, not both), one error format everywhere (for example RFC 9457 problem details:{"type","title","status","detail"}). - Describe it with OpenAPI. A machine-readable spec gives you docs, client SDKs, mock servers and contract tests from one file.
- Return
Locationon create and the full representation on update, so clients don't need a second request to see the result. - Filter, sort and page with query parameters on collections:
GET /orders?status=paid&sort=-created_at&limit=20(lesson 14), not new endpoints like/getPaidOrders. - Know when REST isn't the best fit. Many tiny related reads for one screen may suit GraphQL; high-throughput service-to-service calls often use gRPC. REST is the default for public and web APIs because every tool understands HTTP.
When it breaks
Pick a failure
POST /sendWelcomeEmail retried by the client library
Think before you read on
A shop wants an endpoint that "checks out" a cart: it creates an order, charges the card and empties the cart. That's clearly an action. How would you model it as a resource, and what do you gain?
Reveal
Make the result the resource: POST /orders with {"cart_id": 55} (or POST /checkouts). It returns 201 Created with Location: /orders/901. What you gain: the outcome has an address. The client can GET /orders/901 to see whether the payment succeeded, retry safely by checking whether the order already exists, and support can look it up later. A bare POST /checkout action leaves nothing to look at when the response gets lost halfway through a payment.
Check yourself
1. In REST, where does the verb of an operation go?
Answer
In the HTTP method (GET, POST, PUT, PATCH, DELETE). The URL names the resource with nouns.
2. What should a successful create return?
Answer
201 Created, a Location header with the new resource's URL, and usually the new representation in the body.
3. Why must GET never change data?
Answer
GET is defined as safe. Browsers prefetch it, crawlers follow it, caches replay it and clients retry it freely. Any state change behind a GET will be triggered by accident.
4. When does 405 Method Not Allowed fit better than 404?
Answer
When the resource exists but doesn't support that method, for example PUT /books on a collection. The response should include an Allow header listing the methods that work.
Your challenge: add PUT
Extend the engine with PUT on items:
PUT /books/2with a full body replaces the record: fields that aren't sent are removed.- If the item doesn't exist, return
404(some APIs create it withPUT; pick one and be consistent). - Update the
Allowheader for items toGET, PUT, PATCH, DELETE. - Send
PATCH /books/2 {"year":1815}, thenPUT /books/2 {"title":"Emma"}, thenGET /books/2.
Before you run it, predict what the final GET returns, and what it would return if the last step were a PATCH instead.
You've succeeded when the final GET /books/2 returns {"id":2,"title":"Emma"} with no year, and changing that PUT to PATCH keeps the year field.
Hint: in the starting code PATCH only changes fields that already exist, so for the year step, let PATCH add new fields too.
The mental model
REST names your data as resources with URLs (plural nouns, collections and items, nested only where ownership is real) and acts on them with HTTP's fixed verbs and status codes. GET is safe, POST creates (201 + Location), PUT replaces, PATCH changes part, DELETE removes (204); 404 means no such resource, 405 means no such method. Return representations, not tables, keep each request self-contained, and stay consistent, so a client who has seen one resource can guess the rest.
Station stamp
Finish the chapter
Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.
Go Pro to earn XP →