Thuta Learning
ProjectsWeb Developmentbeginner

GET Single Item

Relax. We'll talk through this in plain words — no textbook voice.

When you need just one item instead of the whole list, use a GET single item route. You can read the ID from the URL using the Express route parameter :id.

javascript
// Add this route after the users array
app.get('/api/users/:id', (req, res) => {
  const id = Number(req.params.id);
  const user = users.find((item) => item.id === id);

  if (!user) {
    return res.status(404).json({
      message: 'User not found'
    });
  }

  res.json(user);
});

req.params.id gives you the ID from the URL as a string. That's why we convert it to a number with Number() and use users.find() to find the matching user. If it's not found, we return a 404 response.

You should see
GET /api/users/2 { "id": 2, "name": "Mya Mya" } GET /api/users/99 { "message": "User not found" }

Info

return res.status(...) is written this way so that once the error response is sent, the rest of the code doesn't keep running.

Easy traps

  • If you forget that req.params.id is a string and strictly compare it against a number ID, the user won't be found. Convert it with Number() or parseInt() instead.

Exercise

This pattern is used on things like user profile detail pages, product detail pages, order detail pages, and article detail pages.

You'll know it worked when: