PUT 的负载与 REST API 中的 POST

Payload for PUT vs POST in REST API

我在采访中被问到以下问题 -

If you are hitting the same request with PUT and with POST http method then what will be the difference in payload?

考虑到我在 REST 方面的工作经验不多,我什至不知道什么是有效载荷。我试过谷歌搜索,但没有找到任何方便的东西。

有人可以帮忙吗?

根据此页面 restfulapi.net PUT 请求应该引用已经存在的项目(例如在连接的数据库中)。换句话说,它旨在更新现有项目。因此负载不必包含项目的所有属性,只需包含您要更新的属性即可。

另一方面 POST 是为了插入新项目。这意味着有效负载应该包含(几乎)所有内容。

事实是,如果您发送更多相同的 PUT 请求,该项目应该与只发送一个 PUT 请求的情况相同。

如果您发送两个相同的 POST 请求,则会创建两个新的相同项目(具有不同的 ID)。这意味着 POST 请求不是幂等的。

编辑:here 也可能有帮助。

I didn't even know what payload is.

面试官可能指的是 HTTP 请求的消息体(参见 RFC 7230)。

If you are hitting the same request with PUT and with POST http method then what will be the difference in payload?

这可能是为了探索您是否理解 HTTP POST method and the HTTP PUT 方法之间的语义差异。

The PUT method requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message payload.

考虑“保存文件”。

POST 的说明不太具体

The POST method requests that the target resource process the representation enclosed in the request according to the resource's own specific semantics.

如果这看起来含糊...你是对的! POST 请求的消息正文几乎可以表示任何内容。 POST 是 HTTP 方法的“垃圾抽屉”——anything not worth standardizing 就在那里。