• 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) : 执行成功,有具体返回描述信息。
  • 相关阅读:
    Vue 设置v-html中元素样式
    2022世界5G大会将设立元宇宙论坛
    Zabbix 6.0:原生高可用(HA)方案部署
    vue3.2新增指令v-memo的使用
    SpringCloud Alibaba - Sentinel 限流规则(案例 + JMeter 测试分析)
    oracle性能优化:ORACLE SQL性能优化系列 (三)[转]
    Q_FLAG与Q_ENUM
    Windows下自动云备份思源笔记到Gitee
    三井住友保险中国区信息技术部负责人陈婧,将出席“ISIG-RPA超级自动化产业发展峰会”
    20个常用的 Git 指令用法
  • 原文地址:https://blog.csdn.net/Apple_wolf/article/details/134317932