Routing & Route Parameters
Map URLs and HTTP methods to handlers — the backbone of every API.
What you will learn
- Handle GET and POST routes
- Read route parameters and query strings
- Send JSON responses
Routes = method + path + handler
A route is the rule that says "when a request comes in for this method and this path, run this function". Each route ties an HTTP method (get to read, post to create, put to update, delete to remove) and a path (the URL) to a handler function.
Here the same path /products has two routes — one for GET and one for POST — because the method makes them different:
app.get("/products", (req, res) => {
res.json([{ id: 1, name: "Keyboard" }, { id: 2, name: "Mouse" }]);
});
app.post("/products", (req, res) => {
res.json({ message: "Product created" });
});Note: Output (visiting /products with a browser, which uses GET):
[{"id":1,"name":"Keyboard"},{"id":2,"name":"Mouse"}]
res.json(...) sends data back as JSON — the standard format APIs use. The GET route returns the list of products; the POST route (triggered when something sends data, not a plain browser visit) replies with a confirmation message. Same URL, different method, different handler.
Route parameters
Often the URL itself contains a value — like which user you want. A :param placeholder in the path captures that piece of the URL, and you read it from req.params. Separately, query strings (the ?key=value part of a URL, like ?sort=price) are read from req.query.
// GET /users/42 → req.params.id is "42"
app.get("/users/:id", (req, res) => {
res.json({ userId: req.params.id });
});
// GET /search?q=react → req.query.q is "react"
app.get("/search", (req, res) => {
res.json({ searching: req.query.q });
});Note: Output (visiting /users/42):
{"userId":"42"}
Output (visiting /search?q=react):
{"searching":"react"}
The :id in /users/:id is a wildcard: visit /users/42 and Express puts "42" in req.params.id. For /search, the part after ? is the query string, so ?q=react becomes req.query.q. (Both arrive as text strings, even when they look like numbers.)
| Source | Where | Example |
|---|---|---|
| Route param | req.params | /users/:id → req.params.id |
| Query string | req.query | ?q=react → req.query.q |
| Request body | req.body | JSON sent in a POST |
Tip: Sending data: res.json(data) returns JSON (what APIs do), res.send(text) returns text/HTML, and res.status(404).json(...) sets the HTTP status code.
Q. For the route /users/:id, how do you read the id from the URL?
✍️ Practice
- Build a
/users/:idroute that returns the id as JSON. - Build a
/greet?name=Asharoute that reads the query and greets by name.
🏠 Homework
- Build routes for a “books” resource: list all, and get one by id.