java Rest api - 更新资源的单个字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47921841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rest api - update single field of resource
提问by user1321466
Lets say I have rest endpoint for my Driver resource. I have PUT method like this
假设我的驱动程序资源有休息端点。我有这样的 PUT 方法
myapi/drivers/{id}
{body of put method}
I need to add functionality which will allow to 'enable' and 'disable' driver
我需要添加允许“启用”和“禁用”驱动程序的功能
Is it good idea to create new endpoint for that like this?
像这样创建新的端点是个好主意吗?
PUT myapi/drivers/{id}/enable/false
or it is better to use existing endpoint ? One problem with using existing endpoint is that driver has lot's of fields(almost 30) and sending all those fields just for updating only 'enabled' or 'disable' driver is something overkill.
还是最好使用现有的端点?使用现有端点的一个问题是驱动程序有很多字段(近 30 个),发送所有这些字段仅用于更新“启用”或“禁用”驱动程序是一种矫枉过正的事情。
What do you think?
你怎么认为?
采纳答案by Sync
This is exactly what the HTTP method PATCH
is made for. It is used in cases where the resource has many fields but you only want to update a few.
这正是 HTTP 方法PATCH
的用途。它用于资源有许多字段但您只想更新少数字段的情况。
Just like with PUT
, you send a request to myapi/drivers/{id}
. However, unlike with PUT
, you only send the fields you want to change in the request body.
就像与一样PUT
,您向 发送请求myapi/drivers/{id}
。但是,与 with 不同PUT
,您只在请求正文中发送要更改的字段。
Creating endpoints like myapi/drivers/{id}/enable
is not very RESTful, as "enable" can't really be called a resource on its own.
创建端点之类myapi/drivers/{id}/enable
的不是很 RESTful,因为“启用”本身并不能真正称为资源。
For an example implementation of a Spring PATCH
endpoint, please see this link.
有关 SpringPATCH
端点的示例实现,请参阅此链接。
回答by whaat
Use PATCH Http metod to update one field
使用 PATCH Http 方法更新一个字段
PATCH myapi/drivers/{id}/enable