Rest API --如何设计好一个Delete方法的API

文章目录

  • 1. 如何定位到当前资源?
  • 2. 如何传参数?
    • 2.1 Path Variable
    • 2.2 Request Parameter
    • 2.3 Request Body
  • 3. 如何判断执行结果

由于Rest API的设计风格,我们是对resource进行CRUD,与之相对应的HTTP方法,也就有GET、POST、PUT、DELETE。
使用DELETE方法,表明对一个资源进行删除操作。那么会带来三个问题:

  • 如何定位到当前资源?
  • 如何传参?
  • 如何判断执行结果?

1. 如何定位到当前资源?

RESTFUL API的设计风格,通过路劲参数Path Variable进行定位资源,例如定位到一个指定账号,即/accounts/{id}

2. 如何传参数?

我们一般有三种参数类型:

  • Path Variable
  • Request Parameter
  • Request Body

2.1 Path Variable

对于Path Variable类型参数,都是支持的。放心大胆用,注意URL encoding就行。

2.2 Request Parameter

对于Request Parameter的参数,也是支持的。

2.3 Request Body

这个需要特别注意,从技术角度来说,这个本身也是支持的,但是不推荐大家使用,不推荐!!

According to Mozilla a DELETE request “may” have a body, compared to a PUT, which should have a body. By this it seems optional whether you want to provide a body for a DELETE request. The RFC states that:
A payload within a DELETE request message has no defined semantics; sending a payload body on a DELETE request might cause some existing implementations to reject the request.

可以看到,带了Request Body的请求可能被reject!
stackOverflow的用户指出,包括Jetty, tomcat在内的server忽略DELETE方法的Request Body,Google cloud HTTPS load balancer直接返回400报错:

User Karmic Coder reports that a lot of clients used to send HTTP requests are unable to send a DELETE with a body, here he mentions Android.
User Ashish reports that Tomcat, Weblogic denies Delete requests that has a payload
User CleverPatrick reports that OpenAPI specification for version 3.0 dropped support for DELETE methods with a body.
User Ben Fried reports that Google cloud HTTPS load balancer will reject delete requests that carry a payload with a 400 status code.
User Parker reports that Sahi Pro strips any provided body data for delete requests.
User evan.leonard reports that Some versions of Tomcat and Jetty seem to ignore an entity body

3. 如何判断执行结果

用好HTTP Status code可以快速判断执行结果。
2XX执行成功,5xx服务器内部错误,4XX客户端错误。

但是要准确使用Status Code:

  • 202 (Accepted) :已经接收到请求,但是还没有执行。
  • A 204 (No Content):已经执行成功,但是没有其他信息返回。
  • A 200 (OK) : 执行成功,有具体返回描述信息。

你可能感兴趣的:(REST,API,DELETE)