RESTful 服务中部分更新的最佳实践 [英] Best practice for partial updates in a RESTful service
问题描述
我正在为客户管理系统编写 RESTful 服务,我正在尝试寻找部分更新记录的最佳实践.例如,我希望调用者能够通过 GET 请求读取完整记录.但是为了更新它,只允许对记录进行某些操作,例如将状态从 ENABLED 更改为 DISABLED.(我有比这更复杂的场景)
I am writing a RESTful service for a customer management system and I am trying to find the best practice for updating records partially. For example, I want the caller to be able to read the full record with a GET request. But for updating it only certain operations on the record are allowed, like change the status from ENABLED to DISABLED. (I have more complex scenarios than this)
出于安全原因,我不希望调用者仅提交包含更新字段的整个记录(这也感觉有点矫枉过正).
I don't want the caller to submit the entire record with just the updated field for security reasons (it also feels like overkill).
是否有推荐的构造 URI 的方法?在阅读 REST 书籍时,RPC 风格的调用似乎不受欢迎.
Is there a recommended way of constructing the URIs? When reading the REST books RPC style calls seem to be frowned upon.
如果以下调用返回 ID 为 123 的客户的完整客户记录
If the following call returns the full customer record for the customer with the id 123
GET /customer/123
<customer>
{lots of attributes}
<status>ENABLED</status>
{even more attributes}
</customer>
我应该如何更新状态?
POST /customer/123/status
<status>DISABLED</status>
POST /customer/123/changeStatus
DISABLED
...
更新:补充问题.如何将业务逻辑调用"合并到 REST api 中?是否有一种商定的方式来做到这一点?并非所有方法本质上都是 CRUD.有些更复杂,例如sendEmailToCustomer(123)"、mergeCustomers(123, 456)"、countCustomers()">
Update: To augment the question. How does one incorporate 'business logic calls' into a REST api? Is there an agreed way of doing this? Not all of the methods are CRUD by nature. Some are more complex, like 'sendEmailToCustomer(123)', 'mergeCustomers(123, 456)', 'countCustomers()'
POST /customer/123?cmd=sendEmail
POST /cmd/sendEmail?customerId=123
GET /customer/count
推荐答案
你基本上有两个选择:
使用
PATCH
(但请注意,您必须定义自己的媒体类型,以指定将发生的确切情况)
Use
PATCH
(but note that you have to define your own media type that specifies what will happen exactly)
对子资源使用 POST
并返回 303 See Other,Location 标头指向主资源.303 的目的是告诉客户端:我已经执行了你的 POST,结果是更新了一些其他资源.请参阅位置标头,了解是哪个资源."POST/303 用于对资源进行迭代添加以构建某些主要资源的状态,并且非常适合部分更新.
Use POST
to a sub resource and return 303 See Other with the Location header pointing to the main resource. The intention of the 303 is to tell the client: "I have performed your POST and the effect was that some other resource was updated. See Location header for which resource that was." POST/303 is intended for iterative additions to a resources to build up the state of some main resource and it is a perfect fit for partial updates.
这篇关于RESTful 服务中部分更新的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!