Idempotent REST APIs

Nikhil Kumar
2 min readAug 16, 2021

--

REST API Header GIF

Idempotence in REST API is designed to consider that API consumers can make mistakes of sending the same request repeatedly.

Idempotence essentially means that the result of a successfully performed request is independent of the number of times it is executed and the repeated identical requests will leave the resource in the same state.

Like in maths adding a number X with 0 will have the same result idenpendent of the no of times it is executed i.e 5 + 0 = 5

HTTP method GET, HEAD, PUT and DELETE are idempotent. In addition to that OPTIONS and TRACE also don’t have any side effects over multiple requests and are inherently idempotent.

The HTTP Methods that don’t even alter any state of the resource are called Safe Methods that means they have read-only semantics and by default all the Safe methods are idempotent.

For considering idempotency the state/action of the entity is considered, the response and status code might differ as in case of DELETE the first request responds with 200 (OK) but further requests will results in 404 (Not found) as the entity was already deleted.

Non-Idempotent HTTP Methods

POST methods are designed to create an entity on the server, on multiple identical POST requests it will create multiple entities on the server which makes it non-Idempotent.

PATCH methods can be idempotent but it isn’t required to be and that’s why it's characterized as non-idempotent. PATCH specifies some merging operation to be done on the resource entity, so a PATCH request can be idempotent if the merging operation is idempotent.

Idempotent PATCH // PATCH { salary: 30000}

Non Idempotent PATCH // PATCH { $increment: 'salary'}

Idempotent HTTP Methods

HTTP GET is a safe method that means it will not going to alter the resources on the server which makes it a perfect candidate for idempotence.

In the case of PUT, the first request will update the entity, and then the rest of N-1 requests will override the same entity again and again, which leaves the resource state the same as it was after the first request.

On multiple DELETE requests, only the first one is going to delete the entity and responds with a 201 (Ok) rest N-1 requests will not be able to find the resource as it was deleted already and responds with 404(Not Found) due to which it's not able to alter the state of the entity after the very first request.

--

--