Skip to main content
Question Protected by gnat
Tweeted twitter.com/StackSoftEng/status/1270958956173721601
edited title
Link
Adam Thompson
  • 1.3k
  • 1
  • 11
  • 16

Designing a REST API with many-to-many relationshipresource relationships?

Source Link
Adam Thompson
  • 1.3k
  • 1
  • 11
  • 16

Designing a REST API with many-to-many relationship?

I'm working to design a REST API to be consumed by a React SPA.

The client-side of the SPA queries data about a relationship between two entities: Team and Player where Teams have many Players and Players can only belong to one Team.

I want to query all the Teams and then get all the Players for each team (which you could imagine would be a fairly typical use-case for these resources in a SPA.)

I can see 3 main approaches:

  1. Expand the /teams endpoint to have some param ?expand=player or something similar that includes a player array for each team. The data comes back nice to be consumed by the react application but now the REST API endpoint is becoming more complex and less compliant to the single-responsibility principle.

  2. Query /teams to get the IDs of all teams and then query each team /team/:id/players. But this will increase the # of requests to the backend, although it will separate responsibilities nicer and make things more explicit.

  3. Query /teams to get the IDs of all teams and then query /players/:ids where :ids is the IDs of all the teams. This is also quite explicit but could result in a huge URL and isn't a nice and tidy.

What approach is generally regarded as the best? Of course all of them have trade-offs, but perhaps I am overlooking some trade-offs?