Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create/update many-to-many relationships in a RESTful API

This is how you add a player to a team in my API:

PUT /teams/1/players/1/

I now want to change the player to another team.

How can I do that?

like image 216
iyourplus Avatar asked Mar 16 '23 14:03

iyourplus


1 Answers

Can I respectfully suggest not doing this? Instead, make /players and /teams both top-level resources. Control what team a player is on using a property on the player. Then you can update a player's team by PUTting the player with the new team value.

Alternately, make a new top-level resource that contains all the player-team mappings, say '/team-memberships'. Then you could query GET /team-memberships?teamId=7 or GET /team-memberships?playerId=2. You can post and delete to this resources to add and remove players from teams.

Conceptually, a player is not a sub-resource of a team. A player is an independent resource that's associated with a team. I think either of the above approaches will give you more flexibility and be easier to understand and work with.

like image 71
Eric Stein Avatar answered Apr 28 '23 20:04

Eric Stein