By the end of this lesson your Bookshop server can hold a conversation. Send GET /hello, and the server answers {"message":"Hello World!"}. Send POST /greet with the name Budi, and the server answers Hello, Budi!. Each takes only a few lines of code.
GET /hello and POST /greet are each called an endpoint: a method and a path together, ready to answer. It works like the counters at a post office. Each counter has a sign and one clerk. You go to the right counter, hand over a form, and the clerk gives you exactly one answer. In an API, the sign is the method + path, the clerk is the function you write, the form is the request, and the answer is the response.
Your first GET endpoint
We continue with the Bookshop API server. When it runs on your laptop, its address is http://localhost:3000 (localhost means your own computer). Its first endpoint only says hello:
app.get("/hello", (req, res) => {
res.json({ message: "Hello World!" });
});
appis the server application. In Express you make it withconst app = express(). In the exercise,appis already there.app.get("/hello", ...)registers an endpoint: when a GET request for the path /hello arrives, run the function next to it.- The function
(req, res) => { ... }is called a handler (the function that handles a request).req(request) holds everything the client sent, andres(response) is the tool you answer with. res.json({ ... })sends that object as JSON. The status is200 OKby default, and the headerContent-Type: application/jsonis set for you.
This is the request and the response, exactly as the Lab shows them:
GET /hello HTTP/1.1
Host: localhost:3000
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 26
{"message":"Hello World!"}
Content-Length: 26 is the body's length in bytes. {"message":"Hello World!"} really is 26 characters, and in this body one character is one byte.
A POST endpoint: read req.body
The second endpoint takes a name from the client and greets that name:
app.post("/greet", (req, res) => {
const { name } = req.body;
res.json({ message: `Hello, ${name}!` });
});
app.postregisters an endpoint for the POST method, the method for sending data to the server.req.bodyis the request's body (what the client sent), already turned from JSON text into an object. Real Express needs one line,app.use(express.json()), at the start of the code for that. In the exercise, that line is already set up.const { name } = req.body;takes thenamefield out of the body (this is called destructuring). It's the same asconst name = req.body.name;.`Hello, ${name}!`is a template literal (a string in backticks that can hold values):${name}is replaced by whatnameholds. The result is the same as"Hello, " + name + "!".
| Request | Body sent | Response |
|---|---|---|
POST /greet |
{"name": "Budi"} |
200 {"message":"Hello, Budi!"} |
POST /greet |
{"name": "Siti"} |
200 {"message":"Hello, Siti!"} |
POST /greet |
{} |
200 {"message":"Hello, undefined!"} |
Look at the last row of the table: the client didn't send name, so name holds undefined, and that word gets printed. This endpoint doesn't check its input (the data the client sent) yet. How to refuse incomplete input such as {} is covered in the Input Validation lesson.
Method + path = one endpoint
The server matches two things at once: the method and the path. GET /hello and POST /greet are two endpoints. GET /greet is also a different endpoint from POST /greet, even though the path is the same.
So if the server only has app.post("/greet", ...) and you send GET /greet, no endpoint matches. The server answers 404 Not Found. Real Express sends it as a small HTML page that says Cannot GET /greet. The POST handler never runs at all.
This means Express never sends 405 Method Not Allowed by itself, even though the HTTP Methods lesson names that answer. If you want 405, add app.all for the same path, after the real route (a route is an endpoint registered in the code, here app.post("/greet", ...)):
app.all("/greet", (req, res) => {
res.set("Allow", "POST").status(405).json({ error: "Method not allowed" });
});
app.all matches any method. Express checks endpoints in the order they are written in the code. Because app.all comes after app.post, app.all only catches the requests that haven't been answered yet, the ones whose method isn't POST. So GET /greet now gets 405 with the header Allow: POST, while POST /greet works as before. res.set("Allow", "POST") sets that header. The exercise does not need this step.
Testing an endpoint
You can't click an endpoint like a button. You need a tool that sends requests.
curl is a tool for sending requests from the terminal (the window where you type commands). Without -X and without -d, curl sends GET. The lines that start with # show the answer that appears in the terminal:
curl http://localhost:3000/hello
# {"message":"Hello World!"}
curl -X POST http://localhost:3000/greet -H "Content-Type: application/json" -d '{"name":"Budi"}'
# {"message":"Hello, Budi!"}
-X POSTpicks the method.-H "Content-Type: application/json"adds the header that says the body is JSON. Without it,express.json()doesn't read the body.-d '{"name":"Budi"}'is the body.
Postman is an app with a graphical interface (GUI) for the same job: pick the method, type the URL, fill in the body, then click Send. Popular alternatives are Insomnia and Thunder Client (a VS Code extension). A browser works too, but typing a URL in the address bar always sends GET. So a browser only suits GET endpoints.
In the exercise, you click Run. The tester registers your endpoints, sends a request to each one, then writes down what came back, for example GET /hello → 200 with its body.
⚠️ Handlers that answer twice, or never answer at all
- Answering twice. One request gets only one response. Say a handler calls
res.send(data);thenres.json({ status: "ok" });(both send an answer). The client gets the first answer, then Express throwsCannot set headers after they are sent to the client. If a handler needs to stop in the middle, writereturn res.json(...). - Never answering. A handler that never calls
res.jsonorres.sendleaves the client waiting until a timeout (the waiting time ends). - Typing the name in.
res.json({ message: "Hello, Budi!" })is only right for Budi. Take the name fromreq.body, so Siti gets "Hello, Siti!". - The wrong method.
app.get("/greet", ...)doesn't answer a POST request. The method in your code has to be the method the client sends.
TL;DR: An endpoint is a method and a path together, such as GET /hello. app.get(path, handler) and app.post(path, handler) register endpoints. A handler is the function (req, res) => { ... } that reads the request from req and answers through res. res.json(object) sends JSON with status 200 and the header Content-Type: application/json. What the client sent is in req.body. For example, const { name } = req.body; takes name, then `Hello, ${name}!` puts it into the greeting. The method and the path must both match, and a request that doesn't match gets 404. One request gets only one response: res.send then res.json (both send an answer) in the same handler throws "Cannot set headers after they are sent". Test endpoints with curl in the terminal, Postman (or Insomnia, Thunder Client), a browser for GET, or the Run button in the exercise.
⚡ Your first GET endpoint
Write:
app.get("/hello", (req, res) => {
res.json({ message: "Hello World!" });
});
Meaning: app.get registers an endpoint, a method and a path together: a GET /hello request runs the handler next to it. The handler is the function (req, res) => { ... }, and res is what you answer with. res.json sends that object as JSON, with status 200 and the header Content-Type: application/json set for you.
⚡ Take data from req.body
Write:
app.post("/greet", (req, res) => {
const { name } = req.body;
res.json({ message: `Hello, ${name}!` });
});
Meaning: app.post registers an endpoint for POST /greet. req.body holds the body the client sent, already turned into an object, and const { name } = req.body; takes name out of it. ${name} is replaced by what name holds, so the body {"name": "Budi"} is answered with Hello, Budi!.
⚡ The method and the path must both match
Guess first: the server only has app.post("/greet", ...), and you send GET /greet. What comes back?
404 Not Found. The path is the same, but the method differs, so no endpoint matches. The POST handler never runs at all.
Meaning: The server matches two things at once: the method and the path. GET /greet and POST /greet are two different endpoints.
⚡ One request, one response
Guess first: the handler calls res.send(data); then res.json({ status: "ok" });, and both send an answer. What does the client get?
Only the first answer. After that, Express throws Cannot set headers after they are sent to the client.
Meaning: One request gets only one response. If a handler needs to stop in the middle, write return res.json(...): return stops the function once its answer is sent.