When should we use PUT and when should we use POST?

来源:互联网 发布:钢琴软件带有键盘乐谱 编辑:程序博客网 时间:2024/04/28 10:45

When should we use PUT and when should we use POST?

The HTTP methods POST and PUT 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 POST to create resources, or use PUT to update resources.

Use PUT 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 PUT a new resource representation of this article directly through a PUT 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 POST 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 CreatedLocation: /articles/63636

As soon as you know the new resource location, you can use PUT again to do updates to the blue stapler article. But as said before: you CAN add new resources through PUT 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 CreatedLocation: /articles/green-stapler

Here, the client decided on the actual resource URL.

Caveats

  • PUT and POST are both unsafe methods. However, PUT is idempotent, while POST is not.
- See more at: http://restcookbook.com/HTTP%20Methods/put-vs-post/#sthash.jQ4qPExo.dpuf
0 0