Friday, July 29, 2016

Difference between HTTP PUT and POST

Difference between PUT and POST

The key difference between PUT and POST is that PUT is idempotent while POST is not. No matter how many times you send a PUT request, the results will be same. POST is not an idempotent method. Making a POST multiple times may result in multiple resources getting created on the server.

Another difference is that, with PUT, you must always specify the complete URI of the resource. This implies that the client should be able to construct the URI of a resource even if it does not yet exist on the server. This is possible when it is the client's job to choose a unique name or ID for the resource, just like creating a user on the server requires the client to choose a user ID. If a client is not able to guess the complete URI of the resource, then you have no option but to use POST.

PUT http://MyService/Persons/
Won't work. PUT requires a complete URI
PUT http://MyService/Persons/1
Insert a new person with PersonID=1 if it does not already exist, or else update the existing resource
POST http://MyService/Persons/
Insert a new person every time this request is made and generate a new PersonID.
POST http://MyService/Persons/1
Update the existing person where PersonID=1

It is clear from the above table that a PUT request will not modify or create more than one resource no matter how many times it is fired (if the URI is same). There is no difference between PUT and POST if the resource already exists, both update the existing resource. The third request (POST http://MyService/Persons/) will create a resource each time it is fired.

HTTP Operations, Safe and Idempotent operations..

Operation performed on server
Read a resource.
Insert a new resource or update if the resource already exists.
Insert a new resource. Also can be used to update an existing resource.
Delete a resource .
List the allowed operations on a resource.
Return only the response headers and no response body.

A Safe operation is an operation that does not have any effect on the original value of the resource. For example, the mathematical operation "divide by 1" is a safe operation because no matter how many times you divide a number by 1, the original value will not change. 

An Idempotent operation is an operation that gives the same result no matter how many times you perform it. For example, the mathematical operation "multiply by zero" is idempotent because no matter how many times you multiply a number by zero, the result is always same. 

Similarly, a Safe HTTP method does not make any changes to the resource on the server. An Idempotent HTTP method has same effect no matter how many times it is performed. Classifying methods as Safe and Idempotent makes it easy to predict the results in the unreliable environment of the Web where the client may fire the same request again.