Identify item by either an ID or a slug in a RESTful API

13,502

Of the three I prefer the third option, it's not uncommon to see that syntax; e.g. parts of Twitter's API allow that syntax: https://dev.twitter.com/rest/reference/get/statuses/show/id

A fourth option is a hybrid approach, where you pick one (say, ID) as the typical access method for single items, but also allow queries based on the slug. E.g.:

GET /items/<id>
GET /items?slug=<slug>
GET /items?id=<id>

Your routing will obvious map /items/id to /items?id=

Extensible to multiple ids/slugs, but still meets the REST paradigm of matching URIs to the underlying data model.

Share:
13,502
Claudio Albertin
Author by

Claudio Albertin

Updated on June 03, 2022

Comments

  • Claudio Albertin
    Claudio Albertin almost 2 years

    I'm currently designing an API and I came a cross a little problem: How should a URL of a RESTful API look like when you should be able to identify an item by either an ID or a slug?

    I could think of three options:

    GET /items/<id>
    GET /items/<slug>
    

    This requires that the slug and the ID are distinguishable, which is not necessarily given in this case. I can't think of a clean solution for this problem, except you do something like this:

    GET /items/id/<id>
    GET /items/slug/<slug>
    

    This would work fine, however this is not the only place I want to identify items by either a slug or an ID and it would soon get very ugly when one wants to implement the same approach for the other actions. It's just not very extendable, which leads us to this approach:

    GET /items?id=<id>
    GET /items?slug=<slug>
    

    This seems to be a good solution, but I don't know if it is what one would expect and thus it could lead to frustrating errors due to incorrect use. Also, it's not so easy - or let's say clean - to implement the routing for this one. However, it would be easily extendable and would look very similar to the method for getting multiple items:

    GET /items?ids=<id:1>,<id:2>,<id:3>
    GET /items?slugs=<slug:1>,<slug:2>,<slug:3>
    

    But this has also a downside: What if someone wants to identify some of the items he want to fetch with IDs, but the others with a slug? Mixing these identifiers wouldn't be easy to achieve with this.

    What is the best and most widely-accepted solution for these problems? In general, what matters while designing such an API?