【发布时间】:2020-09-16 01:53:29
【问题描述】:
想象一个 HTTP REST 端点,其中插入了资源,并且资源被理解为“消息”。每个单独的消息都由一个唯一标识符标识,例如某种 GUID 值。 同一条消息不能重复。
现在,在很多情况下,这适用于PUT 动词,因为它是幂等的。但是请考虑以下情况:
1. The sender sends this message to the receiver:
{
"id": 123,
"text": "original text"
}
2. Now the receiver has this value for the message stored in its database:
{
"id": 123,
"text": "original text"
}
3. For whatever reason, the sender tries to send the same message again, but with amended
text:
{
"id": 123,
"text": "amended text"
}
4. The receiver receives that as well, but since the id field is the same as before, no
action is taken, and this is what the receiver still has in its database:
{
"id": 123,
"text": "original text"
}
接收者行为的原因是每个不同的消息都将由其id 字段唯一标识,并且如果另一个消息以相同的id 发送,则仅将其视为重复消息。此外,尝试像这样更改消息的内容并使用相同的 ID 重新发送它在发件人端是无效行为。
所以从技术上讲,这是幂等的,通常倾向于PUT。但是,此处不允许在任何上下文中进行更新,只需插入即可。那么我们是选择PUT 还是POST,或者这有关系吗? PUT 应该是资源的完整表示,但如果它被简单地丢弃,是否还可以返回 2xx 响应?
就本问题而言,假设使用的路由始终采用<host>/.../message 形式,而不是<host>/.../message/{id} 形式。在这种情况下,我想知道是否自动限制为 <host>/.../message 路由方案意味着应该使用 POST。
【问题讨论】: