描述参数
在 Swagger 中,API 操作参数定义在操作定义中的 parameters
部分下。每个参数都有 name
、值 type
(对于原始值参数)或 schema
(对于请求体),以及可选的 description
。示例如下:
1paths:2 /users/{userId}:3 get:4 summary: Gets a user by ID.5 parameters:6 - in: path7 name: userId8 type: integer9 required: true10 description: Numeric ID of the user to get.
请注意,parameters
是一个数组,因此在 YAML 中,每个参数定义必须以短横线 (-
) 开头。
参数类型
Swagger 根据参数位置区分以下参数类型。位置由参数的 in
键决定,例如 in: query
或 in: path
。
- 查询参数,例如
/users?role=admin
- 路径参数,例如
/users/{id}
- 头部参数,例如
X-MyHeader: Value
- 请求体参数,描述 POST、PUT 和 PATCH 请求的请求体(参见描述请求体)
- 表单参数 – 用于描述
Content-Type
为application/x-www-form-urlencoded
和multipart/form-data
(后者通常用于文件上传)的请求负载的一种请求体参数
查询参数
查询参数是最常见的参数类型。它们出现在请求 URL 的末尾,在问号 (?
) 之后,不同的 name=value
对之间用和号 (&
) 分隔。查询参数可以是必填项或可选项。
1GET /pets/findByStatus?status=available2GET /notes?offset=100&limit=50
使用 in: query
表示查询参数
1parameters:2 - in: query3 name: offset4 type: integer5 description: The number of items to skip before starting to collect the result set.6 - in: query7 name: limit8 type: integer9 description: The numbers of items to return.
查询参数仅支持原始类型。可以有 array
,但 items
必须是原始值类型。不支持对象。
注意:要描述作为查询参数传递的 API 密钥,请改用安全定义。请参阅API 密钥。
路径参数
路径参数是 URL 路径中可以变化的组成部分。它们通常用于指向集合中的特定资源,例如由 ID 标识的用户。一个 URL 可以有多个路径参数,每个都用花括号 { }
表示。
1GET /users/{id}2GET /cars/{carId}/drivers/{driverId}
当客户端发出 API 调用时,每个路径参数都必须替换为实际值。在 Swagger 中,路径参数使用 in: path
和其他必要属性定义。参数名称必须与路径中指定的名称相同。另外,请记住添加 required: true
,因为路径参数始终是必填的。以下是 GET /users/{id}
的示例:
1paths:2 /users/{id}:3 get:4 parameters:5 - in: path6 name: id # Note the name is the same as in the path7 required: true8 type: integer9 minimum: 110 description: The user ID.11 responses:12 200:13 description: OK
路径参数可以是多值的,例如 GET /users/12,34,56
。这可以通过将参数类型指定为 array
来实现。请参阅下面的数组和多值参数。
头部参数
API 调用可能要求 HTTP 请求随附自定义头部。Swagger 允许您将自定义请求头部定义为 in: header
参数。例如,假设调用 GET /ping
需要 X-Request-ID
头部
1GET /ping HTTP/1.12Host: example.com3X-Request-ID: 77e1c83b-7bb0-437b-bc50-a7a58e5660ac
在 Swagger 中,您将按如下方式定义此操作:
1paths:2 /ping:3 get:4 summary: Checks if the server is alive.5 parameters:6 - in: header7 name: X-Request-ID8 type: string9 required: true
以类似的方式,您可以定义自定义响应头部。
注意:Swagger 规范对某些头部有特殊的关键词
头部 | Swagger 关键词 | 更多信息,请参阅... |
---|---|---|
Content-Type |
consumes (请求内容类型)produces (响应内容类型) |
MIME 类型 |
Accept |
produces |
MIME 类型 |
Authorization |
securityDefinitions , security |
认证 |
表单参数
表单参数用于描述 Content-Type
为以下类型的请求负载:
application/x-www-form-urlencoded
(用于 POST 原始值和原始值数组)。multipart/form-data
(用于上传文件或文件与原始数据的组合)。
也就是说,操作的 consumes
属性必须指定这些内容类型之一。表单参数定义为 in: formData
。它们只能是原始类型(字符串、数字、布尔值)或原始类型的数组(这意味着您不能将 $ref
用作 items
值)。此外,表单参数不能与 in: body
参数共存,因为 formData
是一种描述请求体的特定方式。为了说明表单参数,考虑一个 HTML POST 表单:
1<form action="http://example.com/survey" method="post">2 <input type="text" name="name" />3 <input type="number" name="fav_number" />4 <input type="submit" />5</form>
此表单将数据 POST 到表单的端点
1POST /survey HTTP/1.12Host: example.com3Content-Type: application/x-www-form-urlencoded4Content-Length: 295
6name=Amy+Smith&fav_number=321
在 Swagger 中,您可以按如下方式描述该端点:
1paths:2 /survey:3 post:4 summary: A sample survey.5 consumes:6 - application/x-www-form-urlencoded7 parameters:8 - in: formData9 name: name10 type: string11 description: A person's name.12 - in: formData13 name: fav_number14 type: number15 description: A person's favorite number.16 responses:17 200:18 description: OK
要了解如何为文件上传定义表单参数,请参阅文件上传。
必填参数和可选参数
默认情况下,Swagger 将所有请求参数视为可选。您可以添加 required: true
将参数标记为必填项。请注意,路径参数必须为 required: true
,因为它们始终是必填项。
1parameters:2 - in: path3 name: userId4 type: integer5 required: true # <----------6 description: Numeric ID of the user to get.
默认参数值
您可以使用 default
键为可选参数指定默认值。默认值是服务器在客户端未在请求中提供参数值时使用的值。值类型必须与参数的数据类型相同。一个典型的例子是分页参数,如偏移量和限制
1GET /users2GET /users?offset=30&limit=10
假设偏移量默认为 0,限制默认为 20,范围从 0 到 100,您可以按如下方式定义这些参数:
1parameters:2 - in: query3 name: offset4 type: integer5 required: false6 default: 07 minimum: 08 description: The number of items to skip before starting to collect the result set.9 - in: query10 name: limit11 type: integer12 required: false13 default: 2014 minimum: 115 maximum: 10016 description: The numbers of items to return.
常见错误
在使用 default
关键词时有两个常见错误:
- 将
default
与required
参数或属性一起使用,例如与路径参数一起使用。这是没有意义的——如果一个值是必需的,客户端必须始终发送它,并且默认值永远不会被使用。 - 使用
default
指定示例值。这并非默认值的预期用途,并且可能导致某些 Swagger 工具中出现意外行为。规范的某些元素支持example
或examples
关键词用于此目的。
枚举参数
enum
关键词允许您将参数值限制为一组固定值。枚举值必须与参数 type
的类型相同。
1- in: query2 name: status3 type: string4 enum: [available, pending, sold]
更多信息:定义枚举。
数组和多值参数
路径、查询、头部和表单参数可以接受一个值列表,例如:
1GET /users/12,34,56,782GET /resource?param=value1,value2,value33GET /resource?param=value1¶m=value2¶m=value34
5POST /resource6param=value1¶m=value2
多值参数必须使用 type: array
和适当的 collectionFormat
进行定义。
1# color=red,black,white2parameters:3 - in: query4 name: color5 type: array6 collectionFormat: csv7 items:8 type: string
collectionFormat
指定数组格式(单个参数包含多个值或多个同名参数)以及数组项的分隔符。
collectionFormat | 描述 | 示例 |
---|---|---|
csv (默认) |
逗号分隔值。 | foo,bar,baz |
ssv |
空格分隔值。 | foo bar baz |
tsv |
制表符分隔值。 | "foo\tbar\tbaz" |
pipes |
管道分隔值。 | foo|bar|baz |
multi |
多个参数实例而不是多个值。这仅支持 in: query 和 in: formData 参数。 |
foo=value&foo=another_value |
此外,您可以
- 使用
minItems
和maxItems
控制数组大小, - 强制
uniqueItems
, - 将数组项限制为固定的
enum
值集。
例如:
1- in: query2 name: color3 required: false4 type: array5 minItems: 16 maxItems: 57 uniqueItems: true8 items:9 type: string10 enum:11 [12 black,13 white,14 gray,15 red,16 pink,17 orange,18 yellow,19 green,20 blue,21 purple,22 brown,23 ]
您还可以指定如果此参数被省略,服务器将使用的默认数组
1- in: query2 name: sort3 required: false4 type: array5 items:6 type: string7 default: ["-modified", "+id"]
常量参数
您可以将常量参数定义为只有一个可能值的必填参数
1- required: true2 enum: [value]
enum
属性指定可能的值。在此示例中,只能使用一个值,并且这将是 Swagger UI 中用户唯一可选择的值。
注意:常量参数与默认参数值不同。常量参数总是由客户端发送,而默认值是如果客户端未发送参数,服务器将使用的值。
无值参数
查询字符串和表单数据参数可能只有名称而没有值
1GET /foo?metadata2
3POST /something4foo&bar&baz
使用 allowEmptyValue
描述此类参数
1- in: query2 name: metadata3 required: true4 type: boolean5 allowEmptyValue: true # <-----
通用参数
路径所有方法的通用参数
参数可以定义在路径本身下,在这种情况下,参数存在于此路径下描述的所有操作中。一个典型的例子是 GET/PUT/PATCH/DELETE 操作,它们通过路径参数操作相同的资源。
1paths:2 /user/{id}:3 parameters:4 - in: path5 name: id6 type: integer7 required: true8 description: The user ID.9
10 get:11 summary: Gets a user by ID.12 ...13 patch:14 summary: Updates an existing user with the specified ID.15 ...16 delete:17 summary: Deletes the user with the specified ID.18 ...
在操作级别定义的任何额外参数都与路径级别参数一起使用
1paths:2 /users/{id}:3 parameters:4 - in: path5 name: id6 type: integer7 required: true8 description: The user ID.9
10 # GET/users/{id}?metadata=true11 get:12 summary: Gets a user by ID.13 # Note we only define the query parameter, because the {id} is defined at the path level.14 parameters:15 - in: query16 name: metadata17 type: boolean18 required: false19 description: If true, the endpoint returns only the user metadata.20 responses:21 200:22 description: OK
特定路径级别参数可以在操作级别覆盖,但不能删除。
1paths:2 /users/{id}:3 parameters:4 - in: path5 name: id6 type: integer7 required: true8 description: The user ID.9
10 # DELETE /users/{id} - uses a single ID.11 # Reuses the {id} parameter definition from the path level.12 delete:13 summary: Deletes the user with the specified ID.14 responses:15 204:16 description: User was deleted.17
18 # GET /users/id1,id2,id3 - uses one or more user IDs.19 # Overrides the path-level {id} parameter.20 get:21 summary: Gets one or more users by ID.22 parameters:23 - in: path24 name: id25 required: true26 description: A comma-separated list of user IDs.27 type: array28 items:29 type: integer30 collectionFormat: csv31 minItems: 132 responses:33 200:34 description: OK
不同路径中的通用参数
不同的 API 路径可能有一些通用参数,例如分页参数。您可以在全局 parameters
部分定义通用参数,并通过 $ref
在单个操作中引用它们。
1parameters:2 offsetParam: # <-- Arbitrary name for the definition that will be used to refer to it.3 # Not necessarily the same as the parameter name.4 in: query5 name: offset6 required: false7 type: integer8 minimum: 09 description: The number of items to skip before starting to collect the result set.10 limitParam:11 in: query12 name: limit13 required: false14 type: integer15 minimum: 116 maximum: 5017 default: 2018 description: The numbers of items to return.19paths:20 /users:21 get:22 summary: Gets a list of users.23 parameters:24 - $ref: "#/parameters/offsetParam"25 - $ref: "#/parameters/limitParam"26 responses:27 200:28 description: OK29 /teams:30 get:31 summary: Gets a list of teams.32 parameters:33 - $ref: "#/parameters/offsetParam"34 - $ref: "#/parameters/limitParam"35 responses:36 200:37 description: OK
请注意,全局 parameters
不是应用于所有操作的参数——它们只是可以轻松重用的全局定义。
参数依赖
Swagger 不支持参数依赖和互斥参数。在 https://github.com/OAI/OpenAPI-Specification/issues/256 有一个未决的功能请求。您可以做的是在参数描述中记录限制,并在 400 Bad Request 响应中定义逻辑。例如,考虑 /report
端点,它接受相对日期范围 (rdate
) 或精确范围 (start_date
+ end_date
)
1GET /report?rdate=Today2GET /report?start_date=2016-11-15&end_date=2016-11-20
您可以按如下方式描述此端点:
1paths:2 /report:3 get:4 parameters:5 - name: rdate6 in: query7 type: string8 description: >9 A relative date range for the report, such as `Today` or `LastWeek`.10 For an exact range, use `start_date` and `end_date` instead.11 - name: start_date12 in: query13 type: string14 format: date15 description: >16 The start date for the report. Must be used together with `end_date`.17 This parameter is incompatible with `rdate`.18 - name: end_date19 in: query20 type: string21 format: date22 description: >23 The end date for the report. Must be used together with `start_date`.24 This parameter is incompatible with `rdate`.25 responses:26 400:27 description: Either `rdate` or `start_date`+`end_date` are required.
常见问题
何时使用“type”与“schema”?
schema
仅用于 in: body
参数。任何其他参数都期望原始类型,例如 type: string
,或原始类型 array
。
可以将对象作为查询参数吗?
这在OpenAPI 3.0中是可能的,但在 2.0 中不支持。