Part 03 · The Language of the Web

REST and Resource Modeling

RESTAPI

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 hasAction-style API (RPC over HTTP)Resource-style API (REST)
What's the URL?Look it up for every actionGuess from the noun: /orders/7
Which method?Often POST for everythingGET reads, POST creates, PATCH/PUT updates, DELETE removes
Did it work?200 {"success": false} sometimesStatus code: 201, 404, 409, 422...
Can a cache or proxy help?No idea what's safeGET is safe and cacheable by definition
Is retrying safe?Depends, read the docsPUT 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.
a URL per action (RPC style)resources + methods (REST)/getBook?id=2/createBook/updateBookTitle/deleteBook?id=2/addReviewToBook5 actions, 5 URLs to learn/books/books/2/books/2/reviewsPOSTGETPATCHDELETEPOST3 URLs; the method says what to do
On the left, five action-style URLs light up one by one: /getBook?id=2, /createBook, /updateBookTitle, /deleteBook?id=2 and /addReviewToBook. On the right, the same five actions arrive as POST /books, then GET, PATCH and DELETE on /books/2, then POST /books/2/reviews: only three URLs, with the method carrying the verb.

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

  1. Resources are nouns. Users, orders, invoices, reviews. Even processes can be resources: a password reset is POST /password-resets, a payment attempt is POST /payments.
  2. Collections and items. /orders is the collection, /orders/7 is one item in it. Use plural nouns consistently.
  3. Methods carry the verb. GET /orders lists, POST /orders creates, GET /orders/7 reads, PUT /orders/7 replaces, PATCH /orders/7 changes some fields, DELETE /orders/7 removes. The URL never says get, create or delete.
  4. Nesting shows ownership, a level or two deep. /books/2/reviews reads naturally: the reviews of book 2. Deeper chains like /users/1/orders/7/items/3/notes get brittle. Once a child has its own id, it can live at its own top-level URL too (/items/3).
  5. Status codes tell the outcome. 201 Created with a Location header pointing at the new resource, 204 No Content after a delete, 404 when the resource doesn't exist, 405 Method Not Allowed with an Allow header when the method doesn't apply, 409 for conflicts, 422 for invalid data.
  6. 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.
  7. 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.
  8. 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:send or /invoices/7/send). Be consistent, and pick one style per API.
Predict first

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

Step through it

POST /books/2/reviews, from route to response

ClientRouterHandlerDatabase

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?

Try each case

Good URL or action URL?

the orders of user 42
works: A collection nested under its owner. Readable and guessable.

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))
	}
}

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 201 and a Location: /books/1, /books/2 and 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: /books and /books/2 handled list, create, read, change and delete. The nested /books/2/reviews reused exactly the same code.
  • PATCH changed only the title and returned the updated representation.
  • DELETE returned 204, and the next GET /books/1 is a 404: 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 /books is 405 with Allow: 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/comments and /users/1/posts: nested collections, exactly like /books/2/reviews. You could guess both URLs without docs.
  • /posts/9999 is a 404: a resource that doesn't exist.
  • POST to the collection returns 201 and 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_at or createdAt, 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 Location on 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

Try each case

Pick a failure

POST /sendWelcomeEmail retried by the client library
breaks: An action endpoint with side effects, retried automatically. Use idempotency keys or model it as a resource you can check (next lesson).

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/2 with 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 with PUT; pick one and be consistent).
  • Update the Allow header for items to GET, PUT, PATCH, DELETE.
  • Send PATCH /books/2 {"year":1815}, then PUT /books/2 {"title":"Emma"}, then GET /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 →