Getting a Single Product with a Route Parameter
In this section, we’ll see how to return a single product from our product array using a route parameter. We’ll use the same static array of products as before, but keep in mind that in a real application, you would usually fetch the product from a database instead of an in-memory array.
const products: Product[] = [
{ id: 1, name: "Laptop", price: 1200 },
{ id: 2, name: "Headphones", price: 150 },
{ id: 3, name: "Keyboard", price: 80 },
];
- Define a route with a parameter:
- The
:idin/products/:idmeans Express will treat whatever comes after/products/as a variable calledid.
- The
- Extract the ID from the route parameter:
- In your route handler,
req.params.idgives you the value from the URL (as a string).
- In your route handler,
- Convert the ID to a number:
- Since our products have numeric IDs, use
Number(req.params.id).
- Since our products have numeric IDs, use
- Find the product in the array:
- Use the
findmethod to search for a product with a matching ID.
- Use the
- Handle the case where the product isn’t found:
- If no product matches, return a 404 error with a helpful message.
Example:
// GET /products/:id
app.get("/products/:id", (req, res) => {
// 1. Get the id from the route parameter (as a string) and convert to number
// We don't use destructuring here because we need to convert the string to a number
const id = Number(req.params.id);
// 2. Find the product with that id
const product = products.find((p) => p.id === id);
// 3. If not found, return a 404 error
if (!product) {
return res.status(404).json({ error: "Product not found" });
}
// 4. If found, return the product as JSON
res.json(product);
});
Number(req.params.id)gets the ID from the URL and converts it from a string to a number (e.g.,/products/2gives you the string"2", which becomes the number2)- We don’t use destructuring here because we need to convert the value - it’s cleaner to do both operations in one line
products.find()searches for the product with that ID- If not found, we send a 404 error and a helpful message
- If found, we return the product as JSON
Try it out:
- Visit
http://localhost:3000/products/2in your browser or with a tool like Postman to get the product with ID 2.
Getting a Single Product with a Query Parameter
You can also get a single product by passing the ID as a query parameter, for example: /products?id=2.
Important: To test this, you need to comment out the first /products route, because Express will always match the first route it finds with the same path.
// GET /products?id=2
app.get("/products", (req, res) => {
const id = Number(req.query.id);
const product = products.find((p) => p.id === id);
if (!product) {
return res.status(404).json({ error: "Product not found" });
}
res.json(product);
});
- Here, we get the
idfromreq.query.idand use it to find the product - This approach is less common for single resources - route parameters (
/products/:id) are preferred