Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful API design with associations

I'm attempting to build an API for two resources, one with Users, and the other with Movies. Both resources have associations -- a User will have multiple Movies, and a Movie will have multiple Users. Presumably, I'd design my API something like this:

/api/users/
/api/users/:id
/api/users/:id/movies

/api/movies/
/api/movies/:id
/api/movies/:id/users

But here's the issue: I'm also using Backbone.js on the client side to fetch the API data. If If I create a Collection at

/api/users/:id/movies

then this will work well for GET requests, but POST and PUT requests would seemingly then be directed at:

/api/users/:id/movies/:id

But, seemingly, it would be better if it was posted to

/api/movies/:id

instead. Is that correct? How do people generally deal with RestFul associations?

like image 384
bento Avatar asked Nov 03 '22 20:11

bento


2 Answers

Not sure what you mean by "POST and PUT requests would seemingly then be directed at...". Does Backbone.js automatically adds parameters to URLs? If so, you should look at configuring it so that it doesn't do that, because it won't be usable with a REST API. Links provided by a REST API should be the full ones, there's nothing to add or remove from them.

Finally, if you want to associate a movie with a user. You would POST the movie (or just its ID) to:

/api/users/:id/movies
like image 119
laurent Avatar answered Nov 09 '22 15:11

laurent


It is correct. This is because "movies" are independent from "users". Movies can exist without users, so their relationship are actually "associative". To create movies, you don't need users at all, so it makes more sense for the POST URI to create movie to be "POST /api/movies".

Alternative of association in RESTful API that I can think of is to have the list of movie IDs in the GET users API response, e.g. a property named "associatedMovieIDs" which has an array of strings of the IDs of the movies associated to the user. With this, your APIs will then become:

/api/users/
/api/users/:id

/api/movies/
/api/movies/:id
like image 37
Fletcher Sarip Avatar answered Nov 09 '22 15:11

Fletcher Sarip