APIs with Express · Chapter 1 of 29
Hello Express
By the end of this chapter you can build an Express app with a few routes, answer text or JSON with the right label, and start it on a port. 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 in Koramangala keep calling Tapri to ask what is on the menu today, and Ravi reads the list out over the phone in the 4 pm rush. Meera wants it online by Friday, in a form the cafés' apps can read, plus a health check the load balancer can ask every few seconds.
Node's own node:http can do it, but then one function receives every request and sorts them with if statements, setting every header and turning every object into text by hand. Twenty URLs make a long chain of ifs. And a server that opens port 3000 the moment you build it cannot be tested twice at once: the second copy finds the port taken.
The lesson
A first route
With node:http alone, one function sees every request:
import http from 'node:http';
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/hours') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Open 7 am to 11 pm');
} else {
res.writeHead(404);
res.end();
}
});
server.listen(3000);
Express gives each route its own handler:
import express from 'express';
export function createApp() {
const app = express();
app.get('/hours', (req, res) => {
res.send('Open 7 am to 11 pm');
});
app.get('/address', (req, res) => {
res.json({ area: 'Koramangala', city: 'Bengaluru' });
});
return app;
}
When a GET request arrives for that path, Express runs the handler with the request and the response. From the terminal:
$ curl -s -i localhost:3001/address
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 41
ETag: W/"29-5WX8TMufEiNMmRZrVbvByc/uJZs"
Date: Tue, 06 Oct 2026 22:47:01 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"area":"Koramangala","city":"Bengaluru"}
A path nobody registered gets Express's own 404, an HTML page:
$ curl -s localhost:3001/nope
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /nope</pre>
</body>
</html>
Press Next to follow both:
Text or JSON: the label
Every answer carries a Content-Type header, and a client reads that label before the body. res.json turns data into JSON and labels it application/json. res.send with a string labels it HTML:
$ curl -s -i localhost:3001/hours
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 18
ETag: W/"12-WmGWyOqlMq0JADi3exuMnHqEaNg"
Date: Tue, 06 Oct 2026 22:47:01 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Open 7 am to 11 pm
res.send decides by the JavaScript type, not by what the string says, so JSON text is still HTML to it:
const savedHours = JSON.stringify(hours);
app.get('/hours.json', (req, res) => {
res.send(savedHours);
});
$ curl -s -i localhost:3001/hours.json
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 31
ETag: W/"1f-GJbvgqDhWRRtUQwNJsvlBi07hzM"
Date: Tue, 06 Oct 2026 22:47:01 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"open":"7 am","close":"11 pm"}
A partner app that checks the label refuses to parse that. To choose the label yourself, res.type names it before you send:
app.get('/hours.txt', (req, res) => {
res.type('text').send('Open 7 am to 11 pm');
});
That one arrives as Content-Type: text/plain; charset=utf-8. The tempting shortcut, res.json(savedHours), gets the label right and the body wrong: JSON of a string is the string again, in quotes.
$ curl -s localhost:3002/hours.json
"{\"open\":\"7 am\",\"close\":\"11 pm\"}"
Build the app, then listen
createApp builds the app without opening a port. The checks hand it straight to a test client, a fresh app per test, so no two tests fight over a port. Opening one is a separate job:
const server = app.listen(port, (err) => {
if (err) {
console.log('could not start:', err.message);
return;
}
console.log('listening on port', server.address().port);
});
console.log('listening yet?', server.listening);
listen returns the Node http.Server at once, before you know whether the port opened. The callback tells you: Express 5 passes it the error when the port is busy. Started on port 3001, then again while the first one runs:
listening yet? true
listening on port 3001
listening yet? false
could not start: listen EADDRINUSE: address already in use :::3001
Port 0 asks for any free port (listening on port 45357), and server.close() stops the server. Without a callback, app.listen(3001) on a busy port crashes the whole process:
node:events:505
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::3001
Your turn
Your five tasks are at the top, and all five live in exercise.js, marked Task 1 to Task 5. Tasks 1 to 4 are routes inside createApp; task 5 is start, outside it. Kabir asks task 4 as an interview question: be ready to say why a string full of JSON goes out as HTML.
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/01-hello-express
node -e "import('./exercise.js').then((m) => m.createApp().listen(3000))" &
curl -s -i localhost:3000/menu.json
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 /: the greeting
Inside createApp, add GET /. It answers 200 with the text Namaste from Tapri, exactly as written: no extra spaces, no newline.
Send it as a plain string, so it goes out with a Content-Type that starts with text/html.
- Task 2
GET /menu: the menu as JSON
Inside createApp, add GET /menu. It answers 200 with the exported menu array, all three items, as JSON: the Content-Type starts with application/json.
- Task 3
GET /health: status ok for the load balancer
Inside createApp, add GET /health. It answers 200 with { status: 'ok' } as JSON (the Content-Type starts with application/json), and nothing else in the body.
- Task 4 · interview question
Interview: GET /menu.json, the cached menu that arrives as HTML
Fix GET /menu.json. It answers 200 with the cachedMenu string as its body, and its Content-Type must start with application/json. Today the label is text/html, so partner apps refuse to parse it.
cachedMenu is already JSON text. The client parses the body once and must get the menu array back, not a string that holds JSON.
- Task 5
start: open a port and hand back the server
Export start(app, port). It starts app listening on port and returns a Promise that resolves with the Node http.Server once it is listening, so the server answers requests. Port 0 asks for any free port.
If the port cannot be opened, because another server already listens there, the Promise rejects with the error. It must not hang, and the process must not crash.
What you will learn
- Routes: app.get(path, handler) runs one function for one method and path, and Express answers 404 for everything else.
- res.send and res.json: two ways to answer, and the Content-Type label each one puts on the body.
- Building versus listening: createApp builds the app, listen opens a port, so tests never fight over one.
More in First routes
Build "Hello Express" 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.