Deleting a resource using http DELETE

2019-01-16 03:55发布

问题:

So, given that the DELETE verb in Http is idempotent, when I issue the following request, what should happen the second (or third, or fourth, etc...)?

DELETE /person/123

The first time, the resource is deleted and I return a 204 (successful, no content). Should I return a 204 on subsequent calls or a 404 (not found)?

回答1:

As HTTP requests in a stateless system should be independent, the results of one request should not be dependent on a previous request. Consider what should happen if two users did a DELETE on the same resource simultaneously. It makes sense for the second request to get a 404. The same should be true if one user makes two requests.

I am guessing that having DELETE return two different responses does not feel idempotent to you. I find it useful to think of idempotent requests as leaving the system in the same state, not necessarily having the same response. So regardless of whether you DELETE an existing resource, or attempt to DELETE a resource that does not exist, the server resource state is the same.



回答2:

The RESTful web services cookbook is a great resource for this. By chance, its google preview show the page about DELETE (page 11):

The DELETE method is idempotent. This implies that the server must return response code 200 (OK) even if the server deleted the resource in a previous request. But in practice, implementing DELETE as an idempotent operation requires the server to keep track of all deleted resources. Otherwise, it can return a 404 (Not Found).



回答3:

First DELETE: 200 or 204.

Subsequent DELETEs: 200 or 204.

Rationale: DELETE should be idempotent. If you return 404 on a second DELETE, your response is changing from a success code to an error code. The client program may take incorrect actions based on the assumption the DELETE failed.

Example:

  • Suppose your DELETE operation is part of a multi-step operation (or a "saga") executed by the client program.
  • The client program may be a mobile app performing a bank transaction, for example.
  • Let's say the client program has an automatic retry for a DELETE operation (it makes sense, because DELETE is supposed to be idempotent).
  • Let's say the first DELETE was executed successfully, but the 200 response got lost on its way to the client program.
  • The client program will retry the DELETE.
  • If the second attempt returns 404, the client program may cancel the overall operation because of this error code.
  • But because the first DELETE executed successfully on the server, the system may be left at an inconsistent state.
  • If the second attempt returns 200 or 204, the client program will proceed as expected.