So up until now whenever I heard or read someone talk about RESTful API, I had this confusion about POST and PUT being somewhat interchangeable.
But then again I thought, surely thery are not meant to be interchangeable, because in that case why create two different methods? It’s not like we’re talking about a programming language.
Tonight I decided to clear my doubts once and for all, and went to the source of it all:
RFC 2616 is the one that defines the HTTP 1.1 protocol and it’s probably worth a reading for any web developer.
POST vs PUT
Assuming you know what REST is all about, and you know what a “Resource URI” is, this paragraph from the mentioned RFC tells you all you need to know about our “POST vs PUT” dilemma:
- 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.
This is what I get from it.
- With POST, you are contacting the URI of an existing resource to send along a new enclosed entity. E.g. you contact http://api.example.com/books/ and send along the data to create a new book. This definitely sounds like an insert operation to me.
- With PUT, you are contacting the URI of the exact same entity you’re sending along, so you are either updating it (if it already exists) or inserting it (if it does not).
Where does this takes us? That you may add new “records” either with both POST or PUT requests, depending on the case; and you may update records with PUT.
PUT is idempotent
But there’s another important difference between those two methods: PUT is idempotent.
It means that you can make the same identical request over and over again, but the final result and state of the remote system won’t change. That’s because you are always referring to a specific resource.
With POST, instead, each new identical requests will – for example – create a new record. And that’s basically why browsers warn you when you repeat a POST request.
Good to know, just in case 🙂