When to use PUT or POST | - The RESTful cookbook
The RESTful CookBook
How to do stuff RESTful
When should we use PUT and when should we use POST?
The HTTP methods and aren't the HTTP equivalent of the CRUD's create and update. They both serve a different purpose. It's quite possible, valid and even preferred in some occasions, to use to create resources, or use to update resources.
Use when you can update a resource completely through a specific resource. For instance, if you know that an article resides at http://example.org/article/1234, you can a new resource representation of this article directly through a on this URL.
If you do not know the actual resource location, for instance, when you add a new article, but do not have any idea where to store it, you can it to an URL, and let the server decide the actual URL.
PUT /article/1234 HTTP/1.1
<article>
<title>red stapler</title>
<price currency="eur"12.50</price>
</article>POST /articles HTTP/1.1
<article>
<title>blue stapler</title>
<price currency="eur"7.50</price>
</article>
HTTP/1.1 201 Created
Location: /articles/63636As soon as you know the new resource location, you can use again to do updates to the blue stapler article. But as said before: you CAN add new resources through as well. The next example is perfectly valid if your API provides this functionality:
PUT /articles/green-stapler HTTP/1.1
<article>
<title>green stapler</title>
<price currency="eur"9.95</price>
</article>
HTTP/1.1 201 Created
Location: /articles/green-staplerHere, the client decided on the actual resource URL.
Caveats
- and are both unsafe methods. However, is idempotent, while is not.
See also
This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.
Like to contribute? Add your recipe to our github repository.
Looking for Puppet recipies? Try the Puppet CookBook.