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.