Idempotency is a property in which if identical request is called multiple times same results will be produced each time and will not have any side-effect.
Non-idempotency Example:
Assume we have a api to deposit a bank account with money
POST /deposit
Call1: POST /deposit
RequestBody:
{
"amount":1000,
"accountNumber": 1234890
}
Response:
{
"id": 1234,
"amount":1000,
"accountNumber": 1234890,
"cashBalance": 1000,
}
Call2: POST /deposit
RequestBody:
{
"amount":1000,
"accountNumber": 1234890
}
Response:
{
"id": 1234,
"amount":1000,
"accountNumber": 1234890,
"cashBalance": 2000,
}
Even though the above call are identical. Since the above request has a side effect of updating the users cash balance, the amount stored in the persons account will be "2000" instead of "1000".
Idempotency Example:
Assume we have a api to get list of deposits
GET /deposit
Call1: GET /deposit
Response:
[{
"amount":1000,
"accountNumber": 1234890
},
{
"amount":2000,
"accountNumber": 2539894
}]
Call2: GET /deposit
Response:
[{
"amount":1000,
"accountNumber": 1234890
},
{
"amount":2000,
"accountNumber": 2539894
}]
If the above api request is called any number of times, the same response will be returned each time.
Idempotent Http Methods:
GET, PUT, PATCH, DELETE, HEAD, OPTIONS and TRACE http methods are idempotent.
Non-Idempotent Http Methods:
POST method is not idempotent.