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

由于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) : 执行成功,有具体返回描述信息。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值