Search code examples
node.jsrestarchitectureapi-design

Rest API Architecture - GET a resource by alias


I need a help from you about REST Arch. I've a resource and I can retrieve it with the classical GET /resource/ID URI, but this resource has an alias and someone want to GET this resource by calling it via alias.

There is a good way to do so by calling a GET /resource/?alias=x, take the ID and then go to the details /resource/ID.

Do you have any good idea about other ways to do this?


Solution

  • If you want to stay within the constraints of the REST architecture, you definitely need to stay with the verb GET. You can't add other methods.

    Now you need to decide how the resource is named. You have a canonical name (your id), and an alias. One approach is to set up the controller for

    GET /things/:id
    

    so that :id can be either the canonical id or the alias. So you'd have

    app.get('/resources/id', function (req, res) {
      var id = req.params.id;
      if (isAlias(id)) id = resolveAlias(id);
      Thing.findById(id, null, function (err, thing) {
        if (err) res.json(400, err)
        if (thing === null) res.json(404, {"No such id": id})
        res.json(thing)
      });
    });
    

    You can also put in the alias as a query parameter, like you suggested.

    I suspect the only other way might be to use a different url (somethng other than things) but I think this is disingenuous because you want to return the same representation whether or not you use the id or the alias. It should be the same controller, and you should be using GET, so I believe you need to go with the path parameter or query parameter.

    This choice is independent of query rewriting, by the way.