I'm designing a RESTful API, and want to ensure proper adherence to HTTP idempotency rules for PUT and DELETE methods. I understand that idempotency means repeated requests should have the same server-side effect as a single request, but I'm unclear on specific implementation details:
For PUT: If a client sends the same PUT payload multiple times, should the server overwrite the resource every time, or skip the write operation if the data is unchanged?
If the server skips redundant writes, how does it detect whether the data is identical (e.g., comparing hashes, field-by-field checks, or using ETag/If-Match headers)?
For DELETE: If a client sends a DELETE request for a resource that no longer exists, should the server return:
404 Not Found (to indicate the resource is already gone)?
204 No Content (to treat it as a success, since the desired state is achieved)?
MDN's documentation states this quite clearly:
To be idempotent, only the state of the server is considered. The response returned by each request may differ
With regards to PUT
- from the idempotency standpoint, the only thing that matters in the end state of the object.
Whether the server checks the current state of the object, blindly overwrites it, or does something else is inconsequential. As long as at the end of the request's processing the state of the object matches the state described in the request, the handling is considered idempotent.
With regards to DELETE
- as noted above, the return value doesn't effect idempotentcy. The idempotent behavior dictates that the result of a DELETE
request is that the object referenced by it should not exist once the handling of the request is done, whether or not it was there to begin with.
Personally, I'd return a 404 for deleting an object that doesn't exist, but as noted, the behavior will still be idempotent whether you return a 404, 200, or anything else.