Why are REST APIs Idempotent?

·

2 min read

Imagine you’re planning a trip with your friends. All the planning has already been done, and you’re all excited. Now comes the part to book tickets, and you’ve been assigned to do that. While booking air tickets from your place to the destination, you book ten tickets and make payment through Google Pay. The cost is around 50,000, and your bank balance is 1,50,000. So you decide to pay, and the app crashes after you enter your UPI Pin. You wait for some time and again try to pay. This time the payment was successful. You were all happy until you noticed that the current balance of your account is 50,000 and not 1,00,000. This horrifies you, and all that happiness turns into a nightmare.

Luckily what you just imagined cannot occur in these modern times, where APIs have become Idempotent. In simple terms, it means that the idempotent operations will produce the same result even when repeated several times. This ensures that when identical requests are made from the client side, that does not affect the end result. This makes APIs more resilient that enables them to recover fast from failure.

Idempotent HTTP Methods

HEAD | GET | OPTIONS | TRACE

All the above mentioned HTTP methods are read-only. It’s quite logical to figure out that they are by nature Idempotent. You may call these methods any number of times, but the response will be the same as the first time!

PUT

PUT APIs are typically — but not always — used to update the resource state. If you call the PUT API N times, the first request will update the resource; the subsequent N-1 requests will just overwrite the same resource state, essentially altering nothing. As a result, PUT is idempotent.

DELETE

When you issue N identical DELETE requests, the first one deletes the resource and returns a 200 (OK) or 204 response code (No Content).
Other N-1 queries will result in a 404 error (Not Found).
The response is obviously different from the first request, yet there is no change in status for any resource on the server side because the original resource has already been deleted. As a result, DELETE is idempotent.

POST

POST isn’t an idempotent method since repeatedly invoking it may result in inaccurate modifications.” POST APIs often establish new server resources. If you call the POST/payment endpoint with a same request body, you will generate numerous entries. To circumvent this, you must use custom logic to prohibit duplicate records.