Thursday, September 19, 2013

POST vs PUT

Theodore came up to me the other day and said: "Hey John, I want to add this data to the database on the server, do I want to use HTTP POST? Or HTTP PUT?

Good question, Theo. Actually, either POST or PUT can be used to create or update data on the server, but they are different.

The details are elaberated on in the HTTP spec:
"The fundamental difference between the POST and PUT methods is
target resource in a POST request is intended to handle the enclosed
representation as a data-accepting process, such as for a gateway to
some other protocol or a document that accepts annotations. In
contrast, the target resource in a PUT request is intended to take
the enclosed representation as a new or replacement value."

So, to reiterate: POST means you are sending data to a resource that already exists. The resource (which you can look at as a java servlet or a script) processes the data and decides the implications to the online database. PUT means you want the data included with the request to be furthermore represented by the URL of the request. If there is data at the URL already, update it. If there is no data, create it.
"A successful PUT of a given representation would suggest that a subsequent GET on that same target resource will result in an equivalent representation being returned..."
Make sense?

A interesting inherited characteristic of PUT is that it is idiomatic. Which means that multiple requests to the same URL with the same data has no effect. This may come in handy when you lose your connection mid-request.

A hypothical example or using POST and PUT:

Let's say you want to add some data onto a message board website. You find an interesting forum topic, "Glaciers... why do they move so slow?" and want to post a comment. This will probably be done with http POST.
www.glacierforums.com/addCommentToforum?id=235434
Send a request to this URL with a message, and the resource located at "www.glacierforums.com/addCommentToforum" will take the input of "?id=235434" along with your message sent in the request and deal with making sure that this message is added on to the end of forum page.

Now for the same example, you decide that your profile alias "DarthGlacier" is dumb. Nobody references Star Wars nowadays anyway. So you update your user info by sending your new user information (via JSON or whatnot) with a http PUT to this URL.
www.glacierforums.com/users/352343
Your user information, which is located at the URL: www.glacierforums.com/users/352343, has now been updated. A HTTP GET with this URL will return the same user information that you sent to it.

This example assumes you have assumed all authentication privileges needed to write data on to the server.

No comments:

Post a Comment