Idempotent Operations In Restful APIs
Definition
What is Idempotent operation? Idempotent HTTP operations are those which when called one or more multiple times with same request should result into constant effect on the server.
Tell me simple
This basically means for same input idempotent operations give same output no matter how many times operation is performed.
What are the different HTTP methods
PUT and DELETE are supposed to be idempotent HTTP methods. Other HTTP methods like GET, HEAD, OPTIONS & TRACE, which are used to get information and never cause changes on the server can be by default be considered ‘idempotent’.
Important Note
One important note, by output it means effects on the server resource, the response returned by API itself of the operation can vary.
Example
Let’s say there is one car resource on the server represented by uri - /cars/123128
.
The server exposes an api to delete this resource.
When you call this, DELETE API for the first time, the car will be deleted from the server and
api returns 204 which means request processed.
Now when you call the same delete API again, the car is not present on the server which is same as it is deleted, but api
this time can return 404 status code which means not found.
Basically, in above example response of the api changed, but it is still idempotent because the effect on server side is
constant i.e. system removes car.
Additional
Similar concepts in the software world
Interestingly, in functional programming also they promote a similar concept called ‘Pure Functions’. A pure function always returns same output for same input irrelevant of time and external conditions.
For example, f(x) = x*1;
This analogy makes me understand idempotent operations easily.
Upcoming
In coming blogs, we will see what is use case and significance of idempotent operations.