Saturday, 24 March 2018

PUT vs. POST in REST

PUT vs. POST in REST


Sol 1:down vote

PUT is idempotent, where the resource state will be the same if the same operation is executed one time or multiple times.
POST is non-idempotent, where the resource state may become different if the operation is executed multiple times as compared to executing a single time.

Analogy with database query

PUT You can think of similar to "UPDATE STUDENT SET address = "abc" where id="123";
POST You can think of something like "INSERT INTO STUDENT(name, address) VALUES ("abc", "xyzzz");
Student Id is auto generated.
With PUT, if the same query is executed multiple times or one time, the STUDENT table state remains the same.
In case of POST, if the same query is executed multiple times then multiple Student records get created in the database and the database state changes on each execution of an "INSERT" query.
NOTE: PUT needs a resource location (already-resource) on which update needs to happen, whereas POST doesn't require that. Therefore intuitively POST is meant for creation of a new resource, whereas PUT is needed for updating the already existing resource.
Some may come up with that updates can be performed with POST. There is no hard rule which one to use for updates or which one to use for create. Again these are conventions, and intuitively I'm inclined with the above mentioned reasoning and follow it.


Sol 2: 
Both are used for data transmission between client to server, but there are subtle differences between them, which are:
Enter image description here


1 comment: