路径和操作
在 Swagger 术语中,路径是您的 API 公开的端点(资源),例如 /users
或 /reports/summary
,而操作是用于操作这些路径的 HTTP 方法,例如 GET、POST 或 DELETE。
路径
API 路径和操作在 API 规范的全局 paths
部分中定义。
1paths:2 /ping: ...3 /users: ...4 /users/{id}: ...
所有路径都相对于 basePath
(请参阅 API 主机和基本 URL)。完整的请求 URL 构建为 scheme://host/basePath/path
。
路径模板
Swagger 支持路径模板,这意味着您可以使用花括号 {}
将 URL 的一部分标记为路径参数
1/users/{id}2/organizations/{orgId}/members/{memberId}3/report.{format}
API 客户端在进行 API 调用时需要提供适当的参数值,例如 /users/5
或 /users/12
。
操作
对于每个路径,您可以定义用于访问该路径的操作(HTTP 方法)。Swagger 2.0 支持 get
、post
、put
、patch
、delete
、head
和 options
。单个路径可以支持多个操作,例如,GET /users
用于获取用户列表,POST /users
用于添加新用户。Swagger 将唯一的操作定义为路径和 HTTP 方法的组合。这意味着不允许对同一路径使用两个 GET 或两个 POST 方法,即使它们具有不同的参数(参数对唯一性没有影响)。操作的最小示例
1paths:2 /ping:3 get:4 responses:5 200:6 description: OK
更详细的示例,包含参数和响应模式
1paths:2 /users/{id}:3 get:4 summary: Gets a user by ID.5 description: >6 A detailed description of the operation.7 GitHub Flavored Markdown can be used for rich text representation,8 such as **bold**, *italic* and [links](https://swagger.org.cn).9 operationId: getUsers10 tags:11 - users12 produces:13 - application/json14 - application/xml15 parameters:16 - name: id17 in: path18 description: User ID19 type: integer20 required: true21 responses:22 200:23 description: OK24 schema:25 $ref: "#/definitions/User"26 externalDocs:27 url: http://api.example.com/docs/user-operations/28 description: Learn more about User operations provided by this API.29definitions:30 User:31 type: object32 properties:33 id:34 type: integer35 name:36 type: string37 required:38 - id39 - name
操作支持一些可选元素,用于文档目的
- 操作作用的简短
summary
和更长的description
。description
可以是多行,并支持 GitHub Flavored Markdown 用于富文本表示。 tags
用于在 Swagger UI 中对操作进行分组。externalDocs
允许引用包含其他文档的外部资源。
操作参数
Swagger 支持通过路径、查询字符串、标头和请求体传递的操作参数。有关详细信息,请参阅 描述参数。
operationId
每个操作都可以指定唯一的 operationId
。一些代码生成器使用此值来命名代码中的相应方法。
1/users:2 get:3 operationId: getUsers4 summary: Gets all users.5 ...6 post:7 operationId: addUser8 summary: Adds a new user.9 ...10 /user/{id}:11 get:12 operationId: getUserById13 summary: Gets a user by user ID.14 ...
路径中的查询字符串
查询字符串参数不得包含在路径中。它们应该定义为查询参数。不正确
1paths:2 /users?role={role}:
正确
1paths:2 /users:3 get:4 parameters:5 - in: query6 name: role7 type: string8 enum: [user, poweruser, admin]9 required: false
这也意味着不可能有多个仅在查询字符串中不同的路径,例如
1GET /users?firstName=value&lastName=value2GET /users?role=value
这是因为 Swagger 将唯一的操作视为路径和 HTTP 方法的组合,而其他参数并不会使操作变得唯一。相反,您应该使用唯一的路径,例如
1GET /users/findByName?firstName=value&lastName=value2GET /users/findByRole?role=value
标记为已弃用
您可以将特定操作标记为 deprecated
,以指示它们应该停止使用
1/pet/findByTags:2 get:3 deprecated: true
工具可能会以特定方式处理已弃用的操作。例如,Swagger UI 会以不同的样式显示它们