Post

Can we use PUT in place of IDEMPOTENT POST ?

{% raw %}

Consider we have created an idempotent post request. So now the functionalities of PUT and POST are similar. So is it okay to use PUT inplace for POST ?

We should understand what PUT and POST from IETF documentation.

PUT:

https://www.rfc-editor.org/rfc/rfc9110#section-9.3.3

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.

POST:

https://www.rfc-editor.org/rfc/rfc9110#name-put

The POST method requests that the target resource process the representation enclosed in the request according to the resource's own specific semantics. For example, POST is used for the following functions (among others):

1. Providing a block of data, such as the fields entered into an HTML form, to a data-handling process.
2. Posting a message to a bulletin board, newsgroup, mailing list, blog, or similar group of articles.
3. Creating a new resource that has yet to be identified by the origin server.
4. Appending data to a resource's existing representation(s).

From the doc, we can see that both methods can create a resource, then what is the difference.

Even though PUT can create a resource, PUT is an idempotent. Which means, even if you are sending the request 100 times it will return the same response. If the resource is not there it will create, if its there it will update.

But in case of POST request, most of the time it will create a new resource and not idempotent.

So if you are in a situation where to use an idempotent POST request then we can consider PUT. Not really 🙂

As the doc says,

 Proper interpretation of a PUT request 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 POST method rather than PUT.

You can use PUT, only when

  1. The endpoint is idempotent: so safe to redo the request over and over again;
  2. The URI must be the address to the resource being updated.

If a post can create a resource then it should send 201 status code as a response.

{% endraw %}

This post is licensed under CC BY 4.0 by the author.