We can create endpoints that require the client to include search criteria within the path (as opposed to including query strings). For example, suppose the user (via the client) has access to their friend’s User _ids. Then we can create an endpoint that allows the client to get the profile information of a user by passing the User _id in the path. For example the client could send a request using the following method and path where 69153ce6801518f4e58d51ae is a User _id.
GET /user/69153ce6801518f4e58d51ae
The endpoint definition will include a placeholder (e.g. :id) in the path (/user/:id) and the handler can retrieve the value of the placeholder from a request using req.params.id.
A paths can have any number of parameter placeholders so long as the names of the placeholders are distinct.
Below is code for an endpoint that allows a user to retrieve profile information using a User _id in the path. Copy the code into your user.js router file.
router.get('/user/:id', auth, async (req, res) => {
try {
const user = await User.findById(req.params.id).lean()
if (!user) {
res.status(400).send()
}
res.send(user)
}
catch(err) {
console.log(err)
res.status(500).send(err)
}
})
Test With Postman and Push to GitHub
Create a request in Postman and test the endpoint. When you’re satisfied that the endpoint works, push your code to GitHub.