如何设计一个RESTful集合资源? [英] How to design a RESTful collection resource?

查看:84
本文介绍了如何设计一个RESTful集合资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设计一个项目集合"资源.我需要支持以下操作:

I am trying to design a "collection of items" resource. I need to support the following operations:

  1. 创建集合
  2. 删除集合
  3. 将单个项目添加到集合中
  4. 向集合中添加多个项目
  5. 从集合中删除单个项目
  6. 从集合中删除多个项目

这就是我所经历的:

创建集合:

==>
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:

推荐答案

最好使用非位置标识符(例如 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>.

  1. 创建项目和集合是对资源父级的 POST.
  1. Creating items and collections is a POST on the parent of the resource.
  1. 如果客户端有权并有能力生成资源的名称或 ID,您可以使用 PUT.

  • 删除项目和集合是对资源本身的 DELETE.
  • 在父项(集合)上添加多个项目是多个 POST 或多项目 POST.
  • 删除多个项目是对每个资源的 DELETE.我不鼓励多项目 DELETE 有两个原因:

  • Removing items and collections is a DELETE on the resource itself.
  • Adding multiple items is either multiple POST or a multi-item POST on the parent (the collection).
  • Removing multiple items is a DELETE on each resource. I would discourage multi-item DELETE for two reasons:

    1. 批量删除是一种危险的操作(因此,我也不鼓励对非空集合进行 DELETE).
    2. 该操作唯一有意义的目标是父集合,从而使批量 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屋!

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