In traditional REST API, we should define our API like this:
How should i define another 'get one' endpoint for querying data by any other field other than id? For example:
GET /api/things/:title -> get one by title (this sure does not work since the api isn't aware of URL parameter names)
GET /api/things/title/:title ? this does not work for me at all..
GET /api/things?title=whatever (this cannot be defined at all. When i write this in my index.js:
router.get('?title=whatever', controller.getByTitle);
I get this:
SyntaxError: Invalid regular expression: /^?title=whatever\/?$/: Nothing to repeat
at RegExp (native)
ID should be an unique identifier. Given one ID, you should return one resource at most. That's why an URI like GET /api/things/:id
makes sense.
For other properties which may or may not be unique, you can have more than one result, so use the GET /api/things
endpoint and pass query parameters : /api/things?title=mytitle
.
app.get('/api/things', function (req, res) {
console.log(req.query.title); //mytitle
ThingModel.find({
title: req.query.title
}, function (err, things) {
res.send(things);
});
});