upsert (insert/update) 端点的 HTTP 状态代码

HTTP status code for upsert (insert/update) endpoint

我有一个 PUT 端点,它 creates/replace 一个实体,不需要 return Location header 或任何实体 body.

总是 return 204(无内容)是否有意义,或者如果它是一个新实体,它应该是 201,如果它替换实体,它应该是 204

状态代码旨在指示服务器尝试理解和满足请求的结果。这里有两种情况:

  • 如果请求的结果是 创建了 资源,那么 return 201 是有意义的。 Location header 也可以被 return 编辑以识别新创建的资源。如果服务器没有 Location header return,客户端将假定新创建的资源由有效请求 URI 标识。

  • 如果资源已被 修改 并在请求负载中发送表示,则 204200 是合适的状态代码。使用后者,您可以 return 表示资源的新状态。

来自 RFC 7231 的一些相关引述:

4.3.4. 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. [...]

If the target resource does not have a current representation and the PUT successfully creates one, then the origin server MUST inform the user agent by sending a 201 (Created) response. If the target resource does have a current representation and that representation is successfully modified in accordance with the state of the enclosed representation, then the origin server MUST send either a 200 (OK) or a 204 (No Content) response to indicate successful completion of the request. [...]

6.3.1. 200 OK

The 200 (OK) status code indicates that the request has succeeded. The payload sent in a 200 response depends on the request method. For the methods defined by this specification, the intended meaning of the payload can be summarized as:

[...]

PUT, DELETE: a representation of the status of the action;

[...]

6.3.2. 201 Created

The 201 (Created) status code indicates that the request has been fulfilled and has resulted in one or more new resources being created. The primary resource created by the request is identified by either a Location header field in the response or, if no Location field is received, by the effective request URI. [...]

6.3.5. 204 No Content

The 204 (No Content) status code indicates that the server has successfully fulfilled the request and that there is no additional content to send in the response payload body. Metadata in the response header fields refer to the target resource and its selected representation after the requested action was applied. [...]