开发者

REST - HTTP DELETE - semantics - only delete descendants

开发者 https://www.devze.com 2023-03-21 05:08 出处:网络
In our project, a list of all books can be retrieved through REST: GET http://server/api/books/ A specific book can be retrieved as following:

In our project, a list of all books can be retrieved through REST:

GET http://server/api/books/

A specific book can be retrieved as following:

GET http://server/api/books/:id/

Deleting a specific book is easy:

DELETE http://server/api/books/:id/

Now, to my question: what should be the result of the following call:

DELETE http://server/api/books/

Obviously, all books are deleted. But should the resource books/ also be deleted? That is, after the request:

  1. should GET /books/ return 200 OK with an empty list? or
  2. should GET /books/ return 404 not found?

According to the specs, which says that the concrete URI will be gone afterwards, I'd go for the second option. Howev开发者_高级运维er, this makes things complicated and unlogic, in my opinion. It makes more sense to have an empty list of books, instead of no books.

What do you think?


If it makes you feel better, assume that the server has logic that recreates the books resource automatically after it has been deleted. :-)

I'd go for 200 OK and an empty list. If you really don't like that then create a new resource called /books/all

and do

DELETE /Books/all


However, this makes things complicated and unlogic

How? You are requesting that a resource be deleted. That resource is deleted. The result is that it isn't there any more.

If anything, it's confusing to have it still be present after you deleted it.


I think allowing DELETE /books is too risky. Part of a well designed api is to avoid "easy" mistakes from api-client side. It could easily happen that in client code something is going wrong, accidently the id (e.g. empty-string variable) is missing and unintended DELETE /books is sent.

What I would do is to force the client to iterate through DELETE /books/{id} in case he wants to delete all books.

Maybe you can give more input on your use-case: I wonder how likely the use-case is that DELETE /books as root source called (it is quite radical to delete root resources). Maybe you are offering deleting a sub-resource, e.g. /user/{id}/shopping-cart/{id}/books. If it is a more "transient" resource (like shopping-cart is) deleting api for all books would make more sense.

Regarding your other question: For /books I would return 200 and empty list. In collection cases I much prefer empty-lists over 'null' values.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号