One topic that frequently arises when designing REST APIs is idempotency. Let's start by first understanding what the term idempotency means:
Idempotence is the property of certain operations in mathematics, that can be applied multiple times without changing the result beyond the initial application.
In computer science, the term idempotent is used more comprehensively to describe an operation that will produce the same results if executed once or multiple times. - Idempotence - Wikipedia
This is very useful in many situations, as it means that an operation can be repeated or retried as often as necessary without causing unintended side effects.
Idempotency in HTTP
According to RFC 7231 - Section 4.2.2 (the HTTP specification):
A request method is considered "idempotent" if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request.
It goes on to say that by this specification,
DELETE methods are idempotent.
Usually, people take the strictest definition of idempotency and interpret that
DELETE methods MUST return the same response every time they are called.
These points help us debunk this fallacy:
- Using this logic, no method can be idempotent if a system requires authentication, because if a call is made with invalid authentication, the response (
401) will be different than a request with valid authentication (possibly
PUTrequest can return either a
201if the resource is created or
204) if the resource is just updated
DELETErequest can return either a
204if the resource is deleted or a
404if the resource was already deleted
- The RFC for HTTP makes it quite clear: "... repeating the request will have the same intended effect, even if the original request succeeded, though the response might differ."
Due to this, we can conclude that idempotency in REST does not mean that consecutive calls to the same method and resource must return the same response, but rather that consecutive calls to the same method and resource MUST have the same intended effect on the server.
This means that if we issue a
DELETE request to a resource and we get a
204 and a repeated request gets
404 we can still say that the
DELETE method is idempotent.