具有空属性的 PUT
PUT with null attribute
我的 API 有时会收到其中一个布尔属性设置为 null 的 PUT 请求。像这样:
{
"name": "John Doe",
"email": "john.doe@company.com",
"active": null
}
如果这是一个 PATCH,我会简单地忽略该属性,但是如果是 PUT,我该怎么办?我的直觉说:将 active 设置为 false。但我不认为这是正确的 REST 行为。
你怎么看?
根据RFC7231:
6.5.1. 400 Bad Request
400(错误请求)状态码表示服务器无法或
由于某些被认为是
客户端错误(例如,格式错误的请求语法、无效请求
消息框架或欺骗性请求路由)。
我会说您应该拒绝处理未通过 400 Bad Request
响应的数据验证的客户请求。
另请注意:
4.3.4. PUT
PUT 方法请求目标资源的状态是
创建或替换 为表示定义的状态
包含在请求消息负载中。
所以,您不应该只忽略无效的字段值。
但是,如果您跳过数据验证而只接受客户端发送的新资源状态,那么表示将与目标资源不一致,您可以尝试重写请求,或者失败 409 Conflict
(RFC7231):
An origin server SHOULD verify that the PUT representation is
consistent with any constraints the server has for the target
resource that cannot or will not be changed by the PUT. This is
particularly important when the origin server uses internal
configuration information related to the URI in order to set the
values for representation metadata on GET responses. When a PUT
representation is inconsistent with the target resource, the origin
server SHOULD either make them consistent, by transforming the
representation or changing the resource configuration, or respond
with an appropriate error message containing sufficient information
to explain why the representation is unsuitable. The 409 (Conflict)
or 415 (Unsupported Media Type) status codes are suggested, with the
latter being specific to constraints on Content-Type values.
我的 API 有时会收到其中一个布尔属性设置为 null 的 PUT 请求。像这样:
{
"name": "John Doe",
"email": "john.doe@company.com",
"active": null
}
如果这是一个 PATCH,我会简单地忽略该属性,但是如果是 PUT,我该怎么办?我的直觉说:将 active 设置为 false。但我不认为这是正确的 REST 行为。
你怎么看?
根据RFC7231:
6.5.1. 400 Bad Request
400(错误请求)状态码表示服务器无法或 由于某些被认为是 客户端错误(例如,格式错误的请求语法、无效请求 消息框架或欺骗性请求路由)。
我会说您应该拒绝处理未通过 400 Bad Request
响应的数据验证的客户请求。
另请注意:
4.3.4. PUT
PUT 方法请求目标资源的状态是 创建或替换 为表示定义的状态 包含在请求消息负载中。
所以,您不应该只忽略无效的字段值。
但是,如果您跳过数据验证而只接受客户端发送的新资源状态,那么表示将与目标资源不一致,您可以尝试重写请求,或者失败 409 Conflict
(RFC7231):
An origin server SHOULD verify that the PUT representation is consistent with any constraints the server has for the target resource that cannot or will not be changed by the PUT. This is particularly important when the origin server uses internal configuration information related to the URI in order to set the values for representation metadata on GET responses. When a PUT representation is inconsistent with the target resource, the origin server SHOULD either make them consistent, by transforming the representation or changing the resource configuration, or respond with an appropriate error message containing sufficient information to explain why the representation is unsuitable. The 409 (Conflict) or 415 (Unsupported Media Type) status codes are suggested, with the latter being specific to constraints on Content-Type values.