API接口设计

112 阅读1分钟

REST: Representational State Transfer(表述性状态转移)

参考资料

github.com/microsoft/a…

URL 的结构

  • 易于理解和组织
  • 如果是 REST API 不要出现动词,url 里应该都是对资源的描述
  • 最好带版本控制信息

api.hardcore.com/v1.0/users/…

支持的方法

image.png

  • GET /tickets - Retrieves a list of tickets
  • GET /tickets/12 - Retrieves a specific ticket
  • POST /tickets - Creates a new ticket
  • PUT /tickets/12 - Update ticket #12
  • PATCH /tickets/12 - Partially updates ticket #12
  • DELETE /tickets/12 - Deletes ticket #12

幂等:f(x) = f(f(x))

一次请求和多次请求某个资源应该具有同样的副作用

GET

  • 获取资源,不应有副作用,幂等
  • 强调的是相同的副作用,而不是GET的结果相同
  • HEAD 本质和 GET 一样

POST

  • 创建资源,执行动作,有副作用,不是幂等

DELETE

  • 删除资源,有副作用,但满足幂等性

PUT

  • 更新操作,也有副作用,满足幂等性

Standard request headers

image.png

Standard response headers

image.png

自动生成 API 文档

springdoc.org/

<dependency>
    <groupId>org.springdoc</groupId> 
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.2.0</version> 
</dependency>
  • The Swagger UI page will then be available at http://server:port/context-path/swagger-ui.html and the OpenAPI description will be available at the following url for json format: http://server:port/context-path/v3/api-docs