REST API, nested routes without providing identifiers at every nested level

apiapi-designrest

Obviously a RESTful API could contain base routes such as:

api/competitions
api/competitions/{id}
api/teams
api/teams/{id}
api/players
api/players/{id}

And nested routes such as:

api/competitions/{id}/teams
api/competitions/{id}/teams/{id}/players
api/teams/{id}/players
...

But what about the following example (Route A):

api/competitions/{id}/teams/players

So all players, for all teams that are in a certain competition?

Q1: Would this contravene REST design?

Q2: Presumably it does, but is there any documentation that explicitly states this? I have done some research and cannot find anything that rules it out as the examples are all very simplistic.

You could implement (Route B):

api/competitions/{id}/players

instead, and then underneath the logic would ensure that the players are not ALL players (as in api/players) but take into account team and therefore competition – so that players that are without a team are excluded.

However, moving away from this simple example to a more abstract model, there might be scenarios where Route B might be more confusing to an API consumer than Route A.

Q3: Would there ever be a justification for implementing a nested route (like Route A) without all identifiers at every level?

Best Answer

  1. No. REST doesn't care about how your organize your resources, only that individual resources are identified by URLs and that resources are discoverable from other resources. If api/competitions/{id}/teams/players makes sense for your application then use it, as long as users can find a link to it.

  2. Roy Fielding's dissertation on Representational State Transfer, specifically sections 5.2.1.1 Resources and Resource Identifiers and 6.2 REST Applied to URI. Also look into HATEOAS (Hypertext as the Engine of Application State).

  3. Yes, if it is both understood by and convenient for users of your application.

REST is a high-level architectural concept. It's not concerned with how you nest your identifiers. That's up to you and your application requirements. Do what makes sense and be obvious about it.

Related Topic