Wednesday, 28 September 2016

What are Idempotent and Non Idempotent methods?

Idempotent Methods
Lets start by understanding the meaning of Idempotent.
Idempotent means  "unchanged in value following multiplication by itself"

Idempotent HTTP methods are those methods which will not make any modification event after calling multiple times.
For eg - If your client makes a DELETE request by calling this api   -   /myapi/id/50

It will delete the record with Id 50. Now think, what happens when same request gets call multiple times.

Does it make any sense ? Does it effects your server any more?
The answer is NO, why because record with Id = 50 has been already deleted and does not matter how many times you call the same API.

Same for PUT operation.

Suppose below api makes a PUT call to update some information

/myapi/id/55

Now this request will update the record as per given form data. Try to make multiple call with same API, what will happen. It will affect same record again and again and will have no further impact on server side. 

So Idempotent methods are those methods which does not make any modification even after multiple executions. GET, PUT and DELETE are common Idempotent HTTP methods.

Non Idempotent Methods
Non idempotent HTTP methods are those who does effect on server on every call.

POST method is used to create new resources on server side. So, POST is non idempotent methods.
It means every time you make  POST call , it write something at server end.

Safe Methods
Safe methods are those HTTP methods which does not modify the resources. GET and Head are safe methods.
GET only have view rights i.e. it is read only method. So, no matter how many times you execute a GET method, nothing will change at server end.

GET request can be cached.

A very good example is browser refresh button.
Just browse a page and press refresh button or F5 after few moment it will just do a GET request and serves you the same page.
But, if you have submitted a form on a web page in this case if you hit F5 or press refresh button you will get an alert/warning message because it is not a GET request or not a safe method request.


Method
Idempotent
Non Idempotent
SAFE
GET
YES
NO
YES
POST
NO
YES
NO
PUT
YES
NO
NO
DELETE
YES
NO
NO


Hope it will give you a clear idea about Idempotent and Non Idempotent methods.
Happy Coding :)

1 comment:

  1. Very nice blog on HTTP idempotent methods.
    Really it was good and easy to understand.

    ReplyDelete