在REST中处理添加/删除多对多关系的正确方法是什么? [英] What is the proper way to deal with adding/deleting many-to-many relationships in REST?

查看:195
本文介绍了在REST中处理添加/删除多对多关系的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个包含服务器上用户列表的实体,我们希望将其公开为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

我们可以使用PUT进行更新和删除删除?

We can use PUT for updates and DELETE for deletes?

这是对的吗?我去维基百科谈论休息,他们对它的看法是一切都只有1级深。那么也许他们希望你使用PUT / POST并提供整个JSON图并一次更新所有内容?

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

添加用户可能是通过POST一个用户完成,

Adding a user could be done by POSTing a user,

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

删除用户

DELETE /User/5

更新或创建用户可以完成与PUT

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

或只是

DELETE /Entity/1/Users?UserId=5

对于API的用户来说,现实对你的URI看起来并不重要。为自己的理智保持一致是很好的,选择易于使用服务器框架进行调度的方案是很好的,但这不是你的URI的样子,而是你用它们做的重要事情。

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.

这篇关于在REST中处理添加/删除多对多关系的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆