是否应该在 REST API PUT 请求中传递资源及其相关资源的所有字段? [英] Should all the fields of a resource and its related resources be passed in a REST API PUT request?

查看:39
本文介绍了是否应该在 REST API PUT 请求中传递资源及其相关资源的所有字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一张票&评论资源.门票可以有很多评论.在您的更新端点 HTTP PUT/api/tickets// 中,我是否应该要求客户端在更新票证时传递票证的所有字段及其所有注释?

Let's say I have a ticket & comment resource. Tickets can have many comments. In your update endpoint HTTP PUT /api/tickets/<ticket_id>/ , should I require the client to pass all the fields of a ticket + ALL its comments when updating a ticket?

我问了一些开发人员,他们中的一些人说我应该只传递将要修改的字段,因为它更轻、性能更快且更易于使用.有些人说我应该传递票证的所有字段+它的所有评论,因为 PUT 请求应该是幂等的.但是我担心的是评论太多的时候,payload会很大.

I asked some developers and some of them said that I should just pass the fields that will be modified since its lighter, faster in terms of performance and easier to use. And some said that I should pass all the fields of a ticket + ALL its comments since PUT request should be idempotent. But my concern is when there are too many comments, the payload will be very big.

推荐答案

是的,因为 PUT 请求应该完全替换实体更新.如果您想对实体进行部分更新,请使用 PATCH 请求.

Yes, since a PUT request should replace the entity-to-update in it's entirety. If you want to do a partial update of an entity, use a PATCH request.

另请参阅rfc以供参考

HTTP 的 PATCH 方法

扩展超文本传输​​协议 (HTTP) 的几个应用程序需要一个特性来做部分资源修改.

Several applications extending the Hypertext Transfer Protocol (HTTP) require a feature to do partial resource modification.

现有的 HTTP PUT 方法只允许完全替换文档.该提案添加了一个新的 HTTP 方法 PATCH,用于修改现有的 HTTP 资源.

The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

因此,在您的情况下,使用 PATCH 请求进行部分更新可能效率更高.

So in your situation, it's probably a lot more efficient to use a PATCH request to do a partial update.

这篇关于是否应该在 REST API PUT 请求中传递资源及其相关资源的所有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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