angularjsrestexpressmean-stackmean.io

Multiple get API in MEAN.IO (Express, Angular)


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:

I get this:

SyntaxError: Invalid regular expression: /^?title=whatever\/?$/: Nothing to repeat
    at RegExp (native)

Solution

  • 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);
        });
    });