POST versus PUT explained
The use of POST and PUT can be summarized in the following two points:
- PUT is idempotent—it can be repeated, and yields the same result every time. If the resource does not exist, it will create it; otherwise, it will update it.
- POST is nonidempotent—multiple resources will be created if it is called more than once.
The preceding contrast between these verbs is just a general difference. However, there is a very important and significant difference. When using PUT, specifying the complete URI of the resource is necessary. Otherwise, it won't work. For example, the following won't work as it does not specify the exact URI of the author, which can be done by specifying an ID:
PUT http://packtservice.com/Authors/
To fix this, you can send an ID with this URI using something like the following:
PUT http://packtservice.com/Authors/19
created/updated.
This means that the author with the ID 19 will be processed, but if that does not exist, it will be created first. Subsequent requests with this URI will be considered as requests to modify the author resource with an ID of 19.
On the other hand, if we do the same with a POST request like the following, it will create a new author resource with the posted data:
POST http://packtservice.com/Authors/
Interestingly, if you repeat this, you will be responsible for duplicate records with the same data. That is why it is nonidempotent in nature.
Note the following request with POST with an ID. Unlike PUT, POST won't consider this for a new resource, if that is does not exist. It will always be treated as an update request:
POST http://packtservice.com/Authors/19
updated.
The following are the main points to focus on in this section:
- PUT creates or updates one resource, as long as you are calling the same URI
- PUT and POST behave the same, if the resource already exists
- POST, without an ID, will create a resource each time it is fired