Start learning free

LESSON 16 OF 173 · BACKEND: YOUR FIRST API

One Product by ID

Practice

A shop can't write a route for each of its products. Instead, one route has a placeholder in its path: a path parameter, written with a colon in front. In /products/:productId, the placeholder matches whatever is written in that place, so /products/3 matches with productId equal to "3". Express puts the value in req.params, under the same name.

Path parameters are always strings, so turn the value into a number with Number. Here is the same idea on another route:

app.get("/square/:number", (req, res) => {
  const number = Number(req.params.number);
  res.json({ square: number * number });
});

The placeholder also matches text like mug, where Number gives NaN, which means not a number. A route's function can take a third parameter, next. When the value is not a whole number, return next(): it tells Express that this route doesn't answer the request, so Express looks for another route, finds none and answers 404. Express tries the routes in the order they're written, so /products/count still goes to its own route, which comes first.

Once you have the id, find the product with a loop: check each product's id, and when it equals productId, answer with that product, with return in front. return ends the function, so the loop stops there.

Your app must answer:

GET /products/1      →  200  {"id": 1, "name": "Mug", "price": 12, "category": "kitchen"}
GET /products/3      →  200  {"id": 3, "name": "Lamp", "price": 29, "category": "home"}
GET /products/4      →  200  {"id": 4, "name": "Pen", "price": 2, "category": "office"}
GET /products/count  →  200  {"count": 4}
GET /products/mug    →  404  (an HTML error page)

Your task: add a route for /products/:productId with a function that takes req, res and next. Read productId from req.params as a number, return next() when it is not a whole number, then loop over products and answer, as JSON, with the product whose id equals productId.


Assignment
Follow the Coding Tutorial to add the route that answers one product by its id.


Hint
The name after the colon in the path and the name after req.params. must be the same, productId. Number.isInteger(...) tells you whether a value is a whole number. Inside the loop, compare product.id with productId using ===.


STEP 1 OF 7
    Ctrl + Enter to check