REST API UPSERT - USE PUT

 Status codes are meant to indicate the result of the server's attempt to understand and satisfy the request

There are two scenarios here:

  • If a resource has been created as result of the request, it makes sense to return 201. A Location header could also be returned to identify the newly created resource. If no Location header is returned by server, the client will assume that the newly created resource is identified by the effective request URI.

  • If a resource has been modified with the representation sent in the request payload, then 204 or 200 are suitable status codes. With the latter, you could return a representation of the new state of the resource.



Some relevant quotes from the 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:

[...]

PUTDELETE: 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. [...]

Comments

Popular posts from this blog

Best PHP comment DockBlock !

How to fix pgDump dbeaver ?