PUTcreate a resource if it does not exist?
Well, it depends.
The ultimate decision comes down to how the resource identifiers are generated:
- If the server allows the client to generate resource identifiers, then it would be fine to use
PUTfor creating resources.
- On the other hand, if the server generates resource identifiers on behalf of the client, then
POSTshould be used instead of
PUTfor creating resources.
Some parts of the
PUT method definition are quoted below and the last sentence supports what I have just mentioned above (highlight is mine):
PUTmethod 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
PUTsuccessfully 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. […]
Proper interpretation of a
PUTrequest presumes that the user agent knows which target resource is desired. A service that selects a proper URI on behalf of the client, after receiving a state-changing request, SHOULD be implemented using the
POSTmethod rather than
Now, for the sake of completeness, I added below some relevant quotes on the
POST method definition:
POSTmethod requests that the target resource process the representation enclosed in the request according to the resource’s own specific semantics. For example,
POSTis used for the following functions (among others):
- Creating a new resource that has yet to be identified by the origin server;
If one or more resources has been created on the origin server as a result of successfully processing a
POSTrequest, the origin server SHOULD send a
201(Created) response containing a
Locationheader field that provides an identifier for the primary resource created and a representation that describes the status of the request while referring to the new resource(s).
201 status code indicates that a new resource has been created, the
Location header indicate where the newly created resource is located. If no
Location header is provided, then the client should assume that the resource is identified by the effective request URI:
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
Locationheader field in the response or, if no
Locationfield is received, by the effective request URI. […]