Hello, I would like to know the difference between PUT & POST in Restful services.
As I am using Web API, I feel put and post are same or almost same but doesn't have any idea about when to which one.
HTTP Put and post are not equivalent to Create/Update in CRUD operations.
You should use Post to create a new data, suppose for example you are creating a new article, you can pass data using POST
So use POST when you don't have any idea where to store it, you can POST it to an URL, and let the server decide the actual URL.
POST /articles HTTP/1.1 <article> <title>Testing POST</title> <price currency="eur">7.50</price> </article> HTTP/1.1 201 Created Location: /articles/1212
Use PUT when you have an actual location or you can say complete URL with Id to update data for an article(as in above example), you can use PUT
PUT /article/1234 HTTP/1.1 <article> <title>Updated title</title> <price currency="eur">12.50</price> </article>
As soon as you know the new resource location, you can use PUT again to do updates, you can also use PUT for adding new data.
PUT is idempotent, while POST is not.
Better is to choose between PUT and POST based on idempotence of the action.
PUT implies putting a resource - completely replacing whatever is available at the given URL with a different thing. By definition, a PUT is idempotent. Do it as many times as you like, and the result is the same.
x=5 is idempotent. You can PUT a resource whether it previously exists, or not (eg, to Create, or to Update)!
POST updates a resource, adds a subsidiary resource or causes a change. A POST is not idempotent, in the way that
x++ is not idempotent.
by consider above argument, we can say, PUT is for creating when you know the URL of the thing you will create. POST can be used to create when you know the URL of the "factory" or manager for the category of things you want to create.
If you take a look at page 55 of RFC 2616 (“Hypertext Transfer Protocol – HTTP/1.1”), There’s also a handy paragraph to explain the difference between POST and PUT:
The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request – the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource.
But it doesn’t mention anything about the difference between updating/creating, because that’s not what it’s about. It’s about the difference between this:
obj.set_attribute(value) # A POST request.
obj.attribute = value # A PUT request.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly