It is quite easy to confuse in choosing between PUT and POST, when designing RESTful api.
By the end of reading this post you would be able to make a justifying answer for the following questions
- With this request I’m creating a resource object in the back-end, so should I use POST?
- I’ve the identifier but I end up creating a resource object in the back-end with the first request. can I use PUT?
- I don’t have resource identifier in the URL, does this mean I use POST?
- POST and PUT aren’t the HTTP equivalent of the CRUD’s create and update
- Both PUT and POST can be used for creating. * Implementation is left to user.
- Well defined RESTful api will make your client lives easier. Little effort to understand these would make a good difference.
Answer the following questions
Q1. Do you name your actual resource location? or the identifier?
Q2. Are your requests will result in the same state on the server no matter how many times that same request is executed? idempotent?
If Q1 is yes i.e. if you name them use PUT.
If Q2 is yes i.e. idempotent then use PUT.
Below table summarizes recommended return values:
|PUT||404 (Not Found)||200 (OK) or 204 (No Content). 404 (Not Found)|
|POST||201 (Created)||404 (Not Found)|
- PUT is idempotent, it is a nice property, if possible I would PUT when possible.
- PUT without resource identifier may give an impression of update/replace every resource in the entire collection. Unless you wan to apply that update on entire collection.
Consider a following scenario :
Request: PUT /articles Form args: article_id = 10 data = “abcd”
Is it correct to use PUT here?
In my opinion, yes, because I have the resource identifier i.e. article_id. And
GET /articles/10 will return article.
What if I end up creating an article (resource object) with my first request. Is it still correct to use PUT here?
I prefer PUT here as well because I have the identifier and PUT makes it idempotent. So it does more good.
One drawback is you don’t get the 201 response for your first request, just 200 every time(if success) Please note that the decision is yours. These are just ideas taken from some common practices and experience. This article is still under review.