如何设计一个RESTful集合资源? [英] How to design a RESTful collection resource?
问题描述
我正在尝试设计一个项目集合"资源.我需要支持以下操作:
I am trying to design a "collection of items" resource. I need to support the following operations:
- 创建集合
- 删除集合
- 将单个项目添加到集合中
- 向集合中添加多个项目
- 从集合中删除单个项目
- 从集合中删除多个项目
这就是我所经历的:
创建集合:
==>
POST /service
Host: www.myserver.com
Content-Type: application/xml
<collection name="items">
<item href="item1"/>
<item href="item2"/>
<item href="item3"/>
</collection>
<==
201 Created
Location: http://myserver.com/service/items
Content-Type: application/xml
...
删除集合:
==>
DELETE /service/items
<==
200 OK
从集合中删除单个项目:
Removing a single item from the collection:
==>
DELETE /service/items/item1
<==
200 OK
但是,我发现支持其他操作有点棘手,即我可以使用哪些方法:
However, I am finding supporting the other operations a bit tricky i.e. what methods can I use to:
- 将单个或多个项目添加到集合中.(根据 HTTP 1.1 RFC,PUT 似乎不在这里
- 在一次交易中从集合中移除多个项目.(DELETE 似乎也不在这里)
推荐答案
最好使用非位置标识符(例如 UUID)作为集合项,以避免在删除时项的 url 发生变化等问题在它之前的项目.(当然,您仍然可以使用 itemN
或仅使用 N
,只要该编号始终附加在同一项目上,删除后留下空白,但 UUID不那么令人困惑.)
You would be better off using a non-positional identifier such as a UUID for collection items, to avoid problems such as the url of an item changing when you delete an item that precedes it. (Of course, you can still use itemN
or just N
, as long as the number stays attached to the same item at all times, leaving gaps after deletions, but a UUID is less confusing.)
集合的网址为 /service/items/
.每个项目都有 url /service/items/
.
The collection has the url /service/items/
. Each item has the url /service/items/<id>
.
- 创建项目和集合是对资源父级的 POST.
- Creating items and collections is a POST on the parent of the resource.
- 如果客户端有权并有能力生成资源的名称或 ID,您可以使用 PUT.
- 批量删除是一种危险的操作(因此,我也不鼓励对非空集合进行 DELETE).
- 该操作唯一有意义的目标是父集合,从而使批量 DELETE 相对于单项 DELETE 不对称.
如果您确实需要批量删除功能,请通过不同的、明确标记的 API 提供,例如 PURGE/service/items.
If you really need bulk deletion capability, provide it through a different, clearly marked API, such as PURGE /service/items.
这篇关于如何设计一个RESTful集合资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!