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
. ALocation
header could also be returned to identify the newly created resource. If noLocation
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
or200
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:
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 a201
(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 a200
(OK) or a204
(No Content) response to indicate successful completion of the request. [...]
The
200
(OK) status code indicates that the request has succeeded. The payload sent in a200
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;[...]
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 aLocation
header field in the response or, if noLocation
field is received, by the effective request URI. [...]
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