ref – http://stackoverflow.com/questions/630453/put-vs-post-in-rest
Overall:
Both PUT and POST can be used for creating.
You have to ask “what are you performing the action to?” to distinguish what you should be using. Let’s assume you’re designing an API for asking questions. If you want to use POST then you would do that to a list of questions. If you want to use PUT then you would do that to a particular question.
Great both can be used, so which one should I use in my RESTful design:
You do not need to support both PUT and POST.
Which is used is left up to you. But just remember to use the right one depending on what object you are referencing in the request.
Some considerations:
Do you name your URL objects you create explicitly, or let the server decide? If you name them then use PUT. If you let the server decide then use POST.
For example, notice that your URL object you name the user_email explicitly to modify/create. Thus you use PUT.
|
// route to authenticate a user (POST http://localhost:8080/api/:user_email) apiRoutes.put('/:user_email', function(req, res) { .... } |
Notice we let the server make decisions when we create the user. Hence we use POST
|
// http://localhost:8080/createUser app.post('/createUser', function(req, res) { ... } |
PUT is idempotent, so if you PUT an object twice, it has no effect. This is a nice property, so I would use PUT when possible.
note: idempotent means whenever it is applied twice to any value, it gives the same result as if it were applied once.
You can update or create a resource with PUT with the same object URL.
But with POST you can have 2 requests coming in at the same time making modifications to a URL, and they may update different parts of the object.
POST:
Used to modify and update a resource
POST /questions/ HTTP/1.1
Host: wahteverblahblah.com
Note that the following is an error:
POST /questions/ HTTP/1.1
Host: wahteverblahblah.com
If the URL is not yet created, you should not be using POST to create it while specifying the name. This should result in a ‘resource not found’ error because does not exist yet. You should PUT the resource on the server first.
You could though do something like this to create a resources using POST:
POST /questions HTTP/1.1
Host: wahteverblahblah.com
Note that in this case the resource name is not specified, the new objects URL path would be returned to you.
PUT:
Used to create a resource, or overwrite it. While you specify the resources new URL.
For a new resource:
PUT /questions/ HTTP/1.1
Host: wahteverblahblah.com
To overwrite an existing resource:
PUT /questions/ HTTP/1.1
Host: wahteverblahblah.com
I think one cannot stress enough the fact that PUT is idempotent: if the network is botched and the client is not sure whether his request made it through, it can just send it a second (or 100th) time, and it is guaranteed by the HTTP spec that this has exactly the same effect as sending once.