What is the appropriate way to handle adding / deleting multiple-to-many relationships in REST?

advertisements

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?


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.