1

I want to write a JSON API.

My problem is, that sometimes I want to query for an ID, sometimes for a String.

One option would be to add a querystring, for example:

example.com/user/RandomName
example.com/user/1234556778898?id=true

and use it like:

api.get('user/:input', function(req, res) {
  if(req.query.id) {
    User.find({ '_id': req.params.input }, cb);
  } else {
    User.find({ 'name': req.params.input }, cb);
  } 
};

But this seems like bad practice to me, since it leads to a bunch of conditional expressions. Are there more elegant ways?

Stefan
  • 1,041
  • 1
  • 14
  • 28

1 Answers1

2

I would suggest handling two endpoints. One for getting ALL the users and one for getting a SPECIFC user by ID.

  1. example.com/users
  2. example.com/users/:id

The second endpoint can be used to find a specific user by id.

The first endpoint can be used to find all users, but filters can be applied to this endpoint.

For example: example.com/users?name=RandomName

By doing this, you can very easily create a query in your Node service based on the parameters that are in the URL.

api.get('/users', function(req, res) {
    // generate the query object based on URL parameters
    var queryObject = {};
    for (var key in req.query) {
        queryObject[key] = req.query[key];
    }

    // find the users with the filter applied.
    User.find(queryObject, cb);
};  

By constructing your endpoints this way, you are following a RESTful API standard which will make it very easy for others to understand your code and your API. In addition, you are constructing an adaptable API as you can now filter your users by any field by adding the field as a parameter to the URL.

See this response for more information on when to use path parameters vs URL parameters.

Community
  • 1
  • 1
Mike
  • 10,297
  • 2
  • 21
  • 21
  • REST doesn't say anything about endpoint design. +1 for the rest of it, which is spot-on. – Eric Stein Feb 29 '16 at 19:45
  • The only problem I see with the implementation is that anybody from outside is able to query the database and get an insight of the internal structure. This is a potential security issue. – Stefan Mar 01 '16 at 13:18
  • Are you returning the User objects to the client in the response to display information? If you are, it doesn't matter if anyone can query the database using the fields in the URL because they will be able to see the user structure anyway. Also, you can put some checks on the backend to now allow certain fields to be queried if necessary. – Mike Mar 01 '16 at 14:33