APIs with Express · Chapter 2 of 29
Routing
By the end of this chapter you can answer several methods on one path, put routes in an order that works, match paths of any depth, and answer unknown routes yourself. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: First routes
- 5 tasks
- Express
- Free chapter
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.
Why you need this
Partner cafés want to place orders through the API, not only read the menu. Ravi wants to manage today's special from his phone: look at it, replace it, change its price, take it off. Anjali keeps the menu photos in folders by season, and the app must reach any of them.
With only app.get, every action needs its own made-up URL (/special-update, /special-delete), and every partner has to learn your names for them. A photo route written for one folder level misses the rest. And a partner who mistypes a URL gets Express's HTML error page, which their JSON parser chokes on.
The lesson
One path, many methods
A route is a method plus a path, so GET /tables and POST /tables are two routes with two handlers. app.route writes the path once and hangs one handler per method on it:
app.use(express.json());
const tables = [{ table: 4, seats: 6 }];
app.route('/tables')
.get((req, res) => res.json(tables))
.post((req, res) => {
tables.push(req.body);
res.status(201).json(req.body);
});
express.json() parses a JSON body onto req.body (chapter 4 explains it). res.status(201) sets the status before the body: 201 Created says something new now exists.
$ curl -s -i -X POST localhost:3001/tables -H "Content-Type: application/json" -d '{"table":7,"seats":2}'
HTTP/1.1 201 Created
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 21
ETag: W/"15-Tuy4F9/wARYbK19DAwCU4FlPHZ0"
Date: Tue, 06 Oct 2026 22:52:25 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"table":7,"seats":2}
$ curl -s localhost:3001/tables
[{"table":4,"seats":6},{"table":7,"seats":2}]
PUT and PATCH are easy to mix up. Say a notice reads { text: 'Closed on Monday', until: '12 Oct' }. A PUT sends the whole new version: PUT { text: 'Open late' } leaves a notice with no until. A PATCH sends only what changes: PATCH { until: '19 Oct' } keeps the text. A DELETE that worked has nothing left to show, so it answers 204 No Content with an empty body.
First match wins
Express checks routes in the order they were registered and runs the first that matches. A path with a parameter, :id (chapter 3 is all about them), matches any value in that place:
app.get('/cafes/:id', (req, res) => {
const cafe = cafes.find((c) => c.id === req.params.id);
if (!cafe) return res.status(404).json({ error: `No cafe called ${req.params.id}` });
res.json(cafe);
});
app.get('/cafes/nearby', (req, res) => {
res.json(cafes);
});
$ curl -s -i localhost:3001/cafes/nearby
HTTP/1.1 404 Not Found
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 33
ETag: W/"21-HO3UHhoWha1HuSClbYAY2d5aLbM"
Date: Tue, 06 Oct 2026 22:52:25 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"error":"No cafe called nearby"}
Neither handler is wrong, and Express gives no warning. The second route never gets a turn:
Express 5 wildcards
In Express 5 a wildcard needs a name, and its value is an array of segments:
app.get('/recipes/*steps', (req, res) => {
res.json(req.params);
});
$ curl -s localhost:3001/recipes/monsoon/kulhad-chai
{"steps":["monsoon","kulhad-chai"]}
$ curl -s localhost:3001/recipes/ginger
{"steps":["ginger"]}
*steps needs at least one segment, so /recipes alone does not match. A bare *, from an Express 4 tutorial, stops the app before it starts:
PathError [TypeError]: Missing parameter name at index 10: /recipes/*; visit https://git.new/pathToRegexpError for info
at consumeUntil (/workspace/node_modules/path-to-regexp/dist/index.js:108:27)
When nothing matches
A request no route answers gets Express's HTML page, even when the path exists with other methods:
$ curl -s -X DELETE localhost:3003/tables
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot DELETE /tables</pre>
</body>
</html>
app.use with no path runs for every method and path. Registered after every route, it runs only for requests that nothing above answered:
app.use((req, res) => {
res.status(404).send('Nothing here');
});
$ curl -s -X DELETE localhost:3001/tables
Nothing here
Registered first, it would answer every request: first match wins again.
Your turn
Your five tasks are at the top, and all five live in exercise.js, marked Task 1 to Task 5, all inside createApp. Task 5 must come after every other route. Kabir asks task 3 as an interview question: be ready to say why a route that exists never runs.
To try your app by hand in the terminal, start it in the background from the chapter's folder, send it requests with curl, and stop it when you change the code:
cd chapters/02-routing
node -e "import('./exercise.js').then((m) => m.createApp().listen(3000))" &
curl -s -i localhost:3000/menu/popular
kill %1What you build: 5 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
GET and POST /orders: list orders and take new ones
Inside createApp, add GET /orders and POST /orders. Every app starts with the same two orders, { id: 1, item: 'masala-chai', qty: 2 } and { id: 2, item: 'bun-maska', qty: 1 }, and GET /orders answers 200 with the orders array.
POST /orders takes a JSON body { item, qty }. It adds the new order { id, item, qty } to the list and answers 201 with it. Ids go on from 3, then 4, and so on. Without an item it answers 400 with { error: 'item is required' } and adds nothing.
Each createApp() starts fresh: a new app still lists only its own two orders.
- Task 2
/special: today's special with four methods
Inside createApp, answer four methods on /special, chained together with app.route. The special starts as { name: 'Ginger chai', price: 35 }.
GET answers 200 with the special. PUT makes the request body the whole new special, so fields left out are gone, and answers 200 with it. PATCH changes only the fields in the body, keeps the rest, and answers 200 with the result. DELETE removes the special and answers 204 with an empty body.
With no special left (after a DELETE), GET and PATCH answer 404 with { error: 'No special today' }.
- Task 3 · interview question
Interview: GET /menu/popular, the route that never answers
Fix GET /menu/popular. It must answer 200 with the menu items that have popular: true (masala chai and cutting chai), in menu order. Today it answers 404 with { error: 'No item called popular' }.
GET /menu/:id keeps working: GET /menu/bun-maska answers that item, and GET /menu/samosa answers 404 with { error: 'No item called samosa' }.
- Task 4
GET /photos/*file: menu photos at any depth
Inside createApp, add GET /photos/*file. It answers 200 with { file }, where file is everything after /photos/ joined with slashes: GET /photos/monsoon/kulhad.jpg answers { file: 'monsoon/kulhad.jpg' }, GET /photos/stall.jpg answers { file: 'stall.jpg' }, and GET /photos/2026/diwali/lamps.png answers { file: '2026/diwali/lamps.png' }.
GET /photos with nothing after it names no photo and answers 404.
- Task 5
Unknown routes: a JSON 404 that names the method and path
Answer every request that no route answered with 404 and a JSON body (the Content-Type starts with application/json): { error: 'No route for <METHOD> <path>' }, for example { error: 'No route for GET /biscuits' }.
A known path with a method nobody registered counts too: POST /special answers { error: 'No route for POST /special' }, and DELETE /menu answers { error: 'No route for DELETE /menu' }. Real routes, such as GET /menu/parle-g, still answer as before.
What you will learn
- HTTP methods: GET, POST, PUT, PATCH and DELETE on the same path, kept together with app.route.
- First match wins: Express tries routes in the order you registered them, so the order is part of your code.
- Express 5 wildcards: *name matches one segment or many.
- The catch-all: a handler for every request no route answered.
More in First routes
Build "Routing" yourself
Partner cafés want Tapri’s menu online by Friday: you build its API. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.