What is the proper way to deal with adding/deletin

2019-03-18 12:32发布

问题:

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?

回答1:

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.



回答2:

I use your method for parent/child entities, but for many-to-many I use an array in my JSON object representing that entity.

So using your example:

GET /entity/1

would return an entity object something like this:

{"entityID":1,"name":"whatever","users":[1,2,3,4,5]}

PUT would pass in this same object, and update both the entity and the users. Then to get the specific user info:

GET /users/3

Using PUT on users/3 would update the user. PUT on /entity/1 would connect users to entities. Unfortunately, there's not not a lot of good info out there on how to model this sort of thing.