16

Let's say I have an app to manage sporting teams. Potential users have a role of 'coach', 'player', and 'fan'. In many cases they will have to make similar api calls to retrieve info like this:

/api/v1/players    (retrieve all players on their current team)
/api/v1/events     (retrieve all events for their current team)

In other cases roles might have certain features only available to them, like this:

/api/v1/opposing_players/:opposing_player_id  (retrieve scouting info about an opposing player, not available to fans)

My question boils down to... Should I explicitly break out the apis with a prefix for each role? Or should the API only have one base url?

/api/v1/coaches/events
/api/v1/fans/events
/api/v1/players/events

or

/api/v1/events
Msencenb
  • 271

1 Answers1

26

No you shouldn't use level of access as part of the URI.

There is already a standard way to separate API by user access, and that's with authorization. All users should access the same endpoints, and based on the authenticated user's role, or attributes, you can

  • Return 401 Unauthorized - If the user is not authenticated
  • Return 403 Forbidden - If user doesn't have the appropriate role or attributes to access a resource
  • Return different models based on level of access. E.g. coach may be allowed to see each player's birthdate but fans are not allowed. you can show/hide attributes of models based on access.

If you did use a separate API scheme for each role, here are some drawbacks:

  • How do you represent API that are the same for all roles?
  • Must duplicate a lot of routes when a new role is added (e.g. system admin role, or division manager)
  • Changing the name of a role will break the API?
  • Unintuitive - if I'm a coach but I want to access player data, I might think I should access /api/v1/players but really I need to access /api/v1/coaches/players or something
  • How do you represent clients that are players and fans? I.e. multiple roles
  • How do you support allowing unauthenticated clients? I.e. no roles
  • Redundant data - you have to check each user is authorized to access a resource, but now you must also check that the user's role matches the URI . You have to handle the edge case of when the user's role doesn't match the URI role.
  • Changing authorization is an interface-breaking change. Say a coach retires and becomes a fan. They must now change all the endpoints that they used to access.
Samuel
  • 9,237