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 },
];
  1. Define a route with a parameter:
    • The :id in /products/:id means Express will treat whatever comes after /products/ as a variable called id.
  2. Extract the ID from the route parameter:
    • In your route handler, req.params.id gives you the value from the URL (as a string).
  3. Convert the ID to a number:
    • Since our products have numeric IDs, use Number(req.params.id).
  4. Find the product in the array:
    • Use the find method to search for a product with a matching ID.
  5. 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/2 gives you the string "2", which becomes the number 2)
  • 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/2 in 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 id from req.query.id and use it to find the product
  • This approach is less common for single resources - route parameters (/products/:id) are preferred


Repo link

Tags: