Rest – Designing a REST API with resource relationships

apiapi-designrestsingle-responsibilityweb-api

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?

Best Answer

I want to query all the Teams and then get all the Players for each team

How would you do it as a web site?

If you weren't trying to create a "REST API", you would probably just create a single html page that would have all the data you want; one fetch from the client, and tada, you are done.

If there was a lot of data, then you might deliver it as multiple pages, linked together.

But either way, it would just be a big block of HTML, that clients could pull down by getting the link.

Does the spelling of the link matter? Not to the client, they are just fetching it. The server needs to be able to match the correct HTML to the link, but the server can do that any way it likes.

So if you want to put that page in your /teams hierarchy, or in your /players hierarchy, or in a completely separate /league, /reports or /views hierarchy, those are all perfectly fine choices.

The fact that the representation you are using is a JSON document, rather than HTML, or XML, or whatever, doesn't change that.

Part of the point of REST is that its not important that the client be able to disassemble your URI and from it deduce your database schema.

What the server is actually doing to find the correct representation is an implementation detail that we conceal behind the uniform interface.

Related Topic