skip to Main Content

I have this question in my mind for a day, I tried to do some reading from RESTful Web Services Cookbook and other stackoverflow posts, but still did not get a convincing answer to this question:

Assuming I have a database table storing relationships between two users, the relation represents that if user A is following user B (e.g. on Instagram/Twitter).

userId|userId
------|------
userA | userB
userA | userC
....

So now if user A would like to unfollow user B, then should this API be DELETE or POST?

In RESTful Web Services Cookbook page 11, it says:

“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).”

Does this suggest us to not use DELETE whenever we can avoid?

Thanks for any insight on this question!

2

Answers


  1. DELETE is for deleting specific resources. So if DELETE is appropriate for you depends on if you have a single resource that ‘represents’ the follow relationship between two users.

    For example, if you have a resource as such:

    /api/userA/follows/userB
    

    Then it could be said that this resource represents the relationship between the two. It has a unique url, so this url can be deleted at which point I would expect the relationship to be severed.

    Login or Signup to reply.
  2. Building on top of Evert’s answer, the DELETE method is suitable for your needs, as long as you have a resource that represents the relationship between two users.

    The semantic of the DELETE method is defined in the RFC 7231:

    4.3.5. DELETE

    The DELETE method requests that the origin server remove the association between the target resource and its current functionality. […]

    The DELETE method is, in fact, meant to be idempotent, but your quote is fundamentally wrong when it relates idempotency with the status code.

    As I previously mentioned in this answer, idempotency is not related to the status code itself. Idempotency is about the effect produced on the state of the resource on the server, even if the response for the subsequent requests are different from the first request.

    Consider a client performs a DELETE request to delete a resource from the server. The server processes the request, the resource gets deleted and the server returns 204. Then the client repeats the same DELETE request and, as the resource has already been deleted, the server returns 404 and that’s totally fine.

    Despite the different status code received by the client, the effect produced by a single DELETE request is the same effect of multiple DELETE requests to the same URI.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search