Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to deal with adding/deleting many-to-many relationships in REST?

Let's say we have an entity that contains a list of users on the server, and we want to expose this as rest. What is the proper way to do it?

My first guess is something like this:

/entity/1/user/5

We can use PUT for updates and DELETE for deletes?

Is this right? I went to wikipedia where it talks about rest, and their view of it is that everything is only 1 level deep. So maybe they want you to use PUT/POST and give the entire JSON graph and update the entire thing all at once?

like image 586
egervari Avatar asked Dec 23 '10 18:12

egervari


People also ask

Which method is completely deleting in RESTful API?

In RESTful APIs resources are typically deleted using the HTTP DELETE method. The resource that should be deleted is identified by the request URI.

What relationship should a model have with an API interface?

Link objects are used to express structural relationships in the API. So for example, the top-level collections, singleton resources and sub-collections (including actions) are all referenced using link objects. Object links are used to express semantic relationships from the application data model.


1 Answers

Your example is a perfectly valid approach. However in many cases a User can exist outside of the context of just entity. I tend to identify resources in isolation, e.g:

/entity/1
/user/5

To see users associated to an entity I would use:

/entity/1/users

Adding a user could be done by POSTing a user,

POST /entity/1/users
<User>
...
</User>

Deleting a user would be

DELETE /User/5

Updating or creating a user could be done with PUT

PUT /User/6

Removing the association between a user and an entity requires a bit of creativity. You could do

DELETE /Entity/1/User/5 

as you suggested, or something like

DELETE /Entity/1/UserLink?UserId=5

or just

DELETE /Entity/1/Users?UserId=5

It reality is not very important to the user of your API what your URI looks like. It's good to be consistent for your own sanity, it is good to choose schemes that are easy to dispatch with your server framework, but it is not what your URIs look like, it is what you do with them that is important.

like image 60
Darrel Miller Avatar answered Oct 02 '22 20:10

Darrel Miller