我喜欢Thierry Templier 的方法,如文章Implementing Bulk Updates within RESTful Services 中所述。我将在这里总结主要思想,并根据您的上下文进行调整。不过,我确实建议阅读全文:
请求
通常,POST 方法用于将单个元素添加到集合中。所以,我们可以有一个资源,它的方法同时接受单个元素和元素集合。根据输入的有效负载,该处理检测是否必须进行单个或批量添加。
事实上,在资源路径中使用另一个资源,例如 /books/bulk,并不是真正的 RESTful,因此它不是正确的方法。
当创建单个元素时,我们可以有这样的东西:
POST /books
Content-Type: application/json
{
"title": "The Lord of the Rings - The Fellowship of the Ring",
"author": "J. R. R. Tolkien",
(...)
}
以及以下,在批量操作的情况下:
POST /books
Content-Type: application/json
[
{
"title": "The Lord of the Rings - The Fellowship of the Ring",
"author": "J. R. R. Tolkien",
(...)
},
{
"title": "The Lord of the Rings - The Two Towers",
"author": "J. R. R. Tolkien",
(...)
},
(...)
]
响应
创建单个元素时,响应非常简单,通常包含两件事:
- 状态码
201(已创建)
- 标头
Location 包含新创建元素的 URL
201 Created
Location: http://example.com/api/book/{id}
Location 标头接受一个值,并且可以在响应中定义一次。
也就是说,由于 POST 方法的语义取决于 RESTful 服务设计者,我们可以利用标头 Link 来提供此提示,如下所述:
201 Created
Link: <http://example.com/api/book/{id}>, <http://example.com/api/book/{id}>
交易
在批量操作中,您可以考虑使用事务方法:
- 一切正常,所有数据都已插入
- 至少有一个元素存在验证错误且未添加任何内容
- 一个或多个插入失败,所有内容都回滚
422 Unprocessable Entity
Content-type: application/json
[
{
"index": 1,
"messages": [
{
"title": "The title should at least have three characters."
}
]
},
{
"index": 1,
"messages": [
{
"id": "The value of the field it isn't unique."
}
]
},
]
在插入错误的情况下:
500 Internal Server Error
Content-type: application/json
[
{
"index": 1,
"messages": [
"The book can't be added because of the error #22 (description)"
]
},
(...)
]
对于非事务处理,响应的状态码将始终为200,并且响应负载中描述了错误(如果有),如下所示:
200 OK
Content-type: application/json
[
{
"index": 1,
"status": "error",
"messages": [
"The book can't be added because of the error #22 (description)"
]
},
{
"index": 2,
"status": "success",
"auto-generated-id": "43"
},
(...)
]