描述参数
在 OpenAPI 3.0 中,参数在操作或路径的 parameters
部分中定义。要描述一个参数,您需要指定它的 name
、位置 ( in
)、数据类型(由 schema
或 content
定义)和其他属性,例如 description
或 required
。这是一个例子
1paths:2 /users/{userId}:3 get:4 summary: Get a user by ID5 parameters:6 - in: path7 name: userId8 schema:9 type: integer10 required: true11 description: Numeric ID of the user to get
请注意, parameters
是一个数组,因此,在 YAML 中,每个参数定义都必须在前面列出一个破折号 ( -
)。
参数类型
OpenAPI 3.0 根据参数位置区分以下参数类型。位置由参数的 in
键确定,例如 in: query
或 in: path
。
- 路径参数,例如
/users/{id}
- 查询参数,例如
/users?role=admin
- 标头参数,例如
X-MyHeader: Value
- Cookie 参数,它们在
Cookie
标头中传递,例如Cookie: debug=0; csrftoken=BUSe35dohU3O1MZvDCU
路径参数
路径参数是 URL 路径的可变部分。它们通常用于指向集合中的特定资源,例如由 ID 标识的用户。一个 URL 可以有多个路径参数,每个路径参数都用花括号 { }
表示。
1GET /users/{id}2GET /cars/{carId}/drivers/{driverId}3GET /report.{format}
当客户端进行 API 调用时,每个路径参数都必须替换为实际值。在 OpenAPI 中,路径参数使用 in: path
定义。参数名称必须与路径中指定的名称相同。还要记得添加 required: true
,因为路径参数始终是必需的。例如, /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 schema:9 type: integer10 minimum: 111 description: The user ID
包含数组和对象的路径参数可以用不同的方式序列化
- 路径样式扩展(矩阵)——以分号为前缀,例如
/map/point;x=50;y=20
- 标签扩展——以点为前缀,例如
/color.R=100.G=200.B=150
- 简单样式——以逗号分隔,例如
/users/12,34,56
序列化方法由 style
和 explode
关键字指定。要了解更多信息,请参阅参数序列化。
查询参数
查询参数是最常见的参数类型。它们出现在请求 URL 的末尾,在问号 (?
) 之后,不同的 name=value
对用与号 (&
) 分隔。查询参数可以是必需的和可选的。
1GET /pets/findByStatus?status=available2GET /notes?offset=100&limit=50
使用 in: query
表示查询参数
1parameters:2 - in: query3 name: offset4 schema:5 type: integer6 description: The number of items to skip before starting to collect the result set7 - in: query8 name: limit9 schema:10 type: integer11 description: The numbers of items to return
注意: 要描述作为查询参数传递的 API 密钥,请改用 securitySchemes
和 security
。请参阅API 密钥。
查询参数可以是原始值、数组和对象。OpenAPI 3.0 提供了几种在查询字符串中序列化对象和数组的方法。
数组可以序列化为
form
–/products?color=blue,green,red
或/products?color=blue&color=green
,具体取决于explode
关键字spaceDelimited
(与 OpenAPI 2.0 中的collectionFormat: ssv
相同)–/products?color=blue%20green%20red
pipeDelimited
(与 OpenAPI 2.0 中的collectionFormat: pipes
相同)–/products?color=blue|green|red
对象可以序列化为
form
–/points?color=R,100,G,200,B,150
或/points?R=100&G=200&B=150
,具体取决于explode
关键字deepObject
–/points?color[R]=100&color[G]=200&color[B]=150
序列化方法由 style
和 explode
关键字指定。要了解更多信息,请参阅参数序列化。
查询参数中的保留字符
RFC 3986 定义了一组保留字符 :/?#[]@!$&'()*+,;=
,它们用作 URI 组件分隔符。当这些字符需要以字面形式在查询参数值中使用时,它们通常会被百分比编码。例如, /
被编码为 %2F
(或 %2f
),以便参数值 quotes/h2g2.txt
将被发送为
1GET /file?path=quotes%2Fh2g2.txt
如果您想要一个未进行百分比编码的查询参数,请在参数定义中添加 allowReserved: true
1parameters:2 - in: query3 name: path4 required: true5 schema:6 type: string7 allowReserved: true # <-----
在这种情况下,参数值将像这样发送
1GET /file?path=quotes/h2g2.txt
标头参数
API 调用可能需要在 HTTP 请求中发送自定义标头。OpenAPI 允许您将自定义请求标头定义为 in: header
参数。例如,假设调用 GET /ping
需要 X-Request-ID
标头。
1 GET /ping HTTP/1.12 Host: example.com3 X-Request-ID: 77e1c83b-7bb0-437b-bc50-a7a58e5660ac
使用 OpenAPI 3.0,您可以将此操作定义如下:
1paths:2 /ping:3 get:4 summary: Checks if the server is alive5 parameters:6 - in: header7 name: X-Request-ID8 schema:9 type: string10 format: uuid11 required: true
以类似的方式,您可以定义自定义响应标头。标头参数可以是原始类型、数组和对象。数组和对象使用 simple
样式进行序列化。有关更多信息,请参阅参数序列化。
注意: 不允许使用名为 Accept
、Content-Type
和 Authorization
的标头参数。要描述这些标头,请使用相应的 OpenAPI 关键字。
标头 | OpenAPI 关键字 | 有关更多信息,请参阅... |
---|---|---|
Content-Type |
请求内容类型:requestBody.content.<media-type> 响应内容类型: responses.<code>.content.<media-type> |
描述请求体, 描述响应, 媒体类型 |
Accept |
responses.<code>.content.<media-type> |
描述响应, 媒体类型 |
Authorization |
securitySchemes , security |
身份验证 |
Cookie 参数
操作还可以将参数传递到 Cookie
标头中,如 Cookie: name=value
。多个 cookie 参数在同一标头中发送,并用分号和空格分隔。
1GET /api/users2Host: example.com3Cookie: debug=0; csrftoken=BUSe35dohU3O1MZvDCUOJ
使用 in: cookie
定义 cookie 参数。
1parameters:2 - in: cookie3 name: debug4 schema:5 type: integer6 enum: [0, 1]7 default: 08 - in: cookie9 name: csrftoken10 schema:11 type: string
Cookie 参数可以是原始值、数组和对象。数组和对象使用 form
样式进行序列化。有关更多信息,请参阅参数序列化。
注意: 要定义 cookie 身份验证,请改用API 密钥。
必需和可选参数
默认情况下,OpenAPI 将所有请求参数视为可选。您可以添加 required: true
将参数标记为必需。请注意,路径参数必须具有 required: true
,因为它们始终是必需的。
1parameters:2 - in: path3 name: userId4 schema:5 type: integer6 required: true # <----------7 description: Numeric ID of the user to get.
schema vs content
要描述参数内容,您可以使用 schema
或 content
关键字。它们是互斥的,并在不同的场景中使用。在大多数情况下,您将使用 schema
。它允许您描述原始值,以及序列化为字符串的简单数组和对象。数组和对象参数的序列化方法由该参数中使用的 style
和 explode
关键字定义。
1parameters:2 - in: query3 name: color4 schema:5 type: array6 items:7 type: string8
9 # Serialize as color=blue,black,brown (default)10 style: form11 explode: false
content
用于 style
和 explode
未涵盖的复杂序列化场景。例如,如果需要在查询字符串中发送 JSON 字符串,如下所示:
1filter={"type":"t-shirt","color":"blue"}
在这种情况下,您需要将参数 schema
包装到 content/<media-type>
中,如下所示。 schema
定义参数数据结构,而媒体类型(在此示例中为 application/json
)用作外部规范的引用,该规范描述序列化格式。
1parameters:2 - in: query3 name: filter4
5 # Wrap 'schema' into 'content.<media-type>'6 content:7 application/json: # <---- media type indicates how to serialize / deserialize the parameter content8 schema:9 type: object10 properties:11 type:12 type: string13 color:14 type: string
Swagger UI 和 Swagger Editor 用户请注意: Swagger UI 3.23.7+ 和 Swagger Editor 3.6.34+ 支持具有 content
的参数。
默认参数值
在参数模式中使用 default
关键字来指定可选参数的默认值。默认值是当客户端在请求中不提供参数值时,服务器使用的值。值类型必须与参数的数据类型相同。一个典型的例子是诸如 offset
和 limit
之类的分页参数。
1GET /users2GET /users?offset=30&limit=10
假设 offset
默认为 0,而 limit
默认为 20,范围为 0 到 100,您可以将这些参数定义为:
1parameters:2 - in: query3 name: offset4 schema:5 type: integer6 minimum: 07 default: 08 required: false9 description: The number of items to skip before starting to collect the result set.10 - in: query11 name: limit12 schema:13 type: integer14 minimum: 115 maximum: 10016 default: 2017 required: false18 description: The number of items to return.
常见错误
使用 default
关键字时,有两个常见错误:
- 将
default
与required
参数或属性一起使用,例如,使用路径参数。这没有意义——如果某个值是必需的,客户端必须始终发送它,并且永远不会使用默认值。 - 使用
default
指定示例值。这不是default
的预期用途,并且可能在某些 Swagger 工具中导致意外行为。请改用example
或examples
关键字。请参阅添加示例。
枚举参数
您可以通过将 enum
添加到参数的 schema
,将参数限制为一组固定值。枚举值必须与参数数据类型相同。
1parameters:2 - in: query3 name: status4 schema:5 type: string6 enum:7 - available8 - pending9 - sold
更多信息:定义枚举。
常量参数
您可以将常量参数定义为仅具有一个可能值的必需参数:
1parameters:2 - in: query3 name: rel_date4 required: true5 schema:6 type: string7 enum:8 - now
enum
属性指定可能的值。在此示例中,只能使用一个值,这将是 Swagger UI 中唯一可供用户选择的值。
注意: 常量参数与默认参数值不同。常量参数始终由客户端发送,而默认值是如果客户端未发送参数,服务器使用的值。
空值和可空参数
查询字符串参数可能只有名称而没有值,如下所示:
1GET /foo?metadata
使用 allowEmptyValue
来描述此类参数:
1parameters:2 - in: query3 name: metadata4 schema:5 type: boolean6 allowEmptyValue: true # <-----
OpenAPI 3.0 还支持模式中的 nullable
,允许操作参数具有 null
值。例如,以下模式对应于 C# 中的 int?
和 Java 中的 java.lang.Integer
:
1schema:2 type: integer3 format: int324 nullable: true
注意: nullable
与可选参数或空值参数不同。 nullable
表示参数值可以为 null
。特定实现可以选择将不存在的或空值的参数映射到 null
,但严格来说,它们不是同一件事。
参数示例
您可以为参数指定一个 example
或多个 examples
。示例值应与参数模式匹配。单个示例:
1parameters:2 - in: query3 name: limit4 schema:5 type: integer6 minimum: 17 example: 20
多个命名示例:
1parameters:2 - in: query3 name: ids4 description: One or more IDs5 required: true6 schema:7 type: array8 items:9 type: integer10 style: form11 explode: false12 examples:13 oneId:14 summary: Example of a single ID15 value: [5] # ?ids=516 multipleIds:17 summary: Example of multiple IDs18 value: [1, 5, 7] # ?ids=1,5,7
有关详细信息,请参阅添加示例。
已弃用的参数
使用 deprecated: true
将参数标记为已弃用。
1- in: query2 name: format3 required: true4 schema:5 type: string6 enum: [json, xml, yaml]7 deprecated: true8 description: Deprecated, use the appropriate `Accept` header instead.
通用参数
路径的所有方法的常用参数
可以在路径级别而不是操作级别定义路径的所有操作共享的参数。路径级参数由该路径的所有操作继承。一个典型的用例是操作通过路径参数访问的资源的 GET/PUT/PATCH/DELETE 操作。
1paths:2 /user/{id}:3 parameters:4 - in: path5 name: id6 schema:7 type: integer8 required: true9 description: The user ID10 get:11 summary: Gets a user by ID12 ...13 patch:14 summary: Updates an existing user with the specified ID15 ...16 delete:17 summary: Deletes the user with the specified ID18 ...
在操作级别定义的任何额外参数都与路径级参数一起使用。
1paths:2 /users/{id}:3 parameters:4 - in: path5 name: id6 schema:7 type: integer8 required: true9 description: The user ID.10
11 # GET/users/{id}?metadata=true12 get:13 summary: Gets a user by ID14 # Note we only define the query parameter, because the {id} is defined at the path level.15 parameters:16 - in: query17 name: metadata18 schema:19 type: boolean20 required: false21 description: If true, the endpoint returns only the user metadata.22 responses:23 "200":24 description: OK
可以在操作级别覆盖特定的路径级参数,但不能删除。
1paths:2 /users/{id}:3 parameters:4 - in: path5 name: id6 schema:7 type: integer8 required: true9 description: The user ID.10
11 # DELETE /users/{id} - uses a single ID.12 # Reuses the {id} parameter definition from the path level.13 delete:14 summary: Deletes the user with the specified ID.15 responses:16 "204":17 description: User was deleted.18
19 # GET /users/id1,id2,id3 - uses one or more user IDs.20 # Overrides the path-level {id} parameter.21 get:22 summary: Gets one or more users by ID.23 parameters:24 - in: path25 name: id26 required: true27 description: A comma-separated list of user IDs.28 schema:29 type: array30 items:31 type: integer32 minItems: 133 explode: false34 style: simple35 responses:36 "200":37 description: OK
各种路径的通用参数
不同的 API 路径可能具有通用参数,例如分页参数。您可以在全局 components
部分的参数下定义通用参数,并通过 $ref
在其他地方引用它们。
1components:2 parameters:3 offsetParam: # <-- Arbitrary name for the definition that will be used to refer to it.4 # Not necessarily the same as the parameter name.5 in: query6 name: offset7 required: false8 schema:9 type: integer10 minimum: 011 description: The number of items to skip before starting to collect the result set.12 limitParam:13 in: query14 name: limit15 required: false16 schema:17 type: integer18 minimum: 119 maximum: 5020 default: 2021 description: The numbers of items to return.22
23paths:24 /users:25 get:26 summary: Gets a list of users.27 parameters:28 - $ref: "#/components/parameters/offsetParam"29 - $ref: "#/components/parameters/limitParam"30 responses:31 "200":32 description: OK33 /teams:34 get:35 summary: Gets a list of teams.36 parameters:37 - $ref: "#/components/parameters/offsetParam"38 - $ref: "#/components/parameters/limitParam"39 responses:40 "200":41 description: OK
请注意,在 components
中定义的参数不是应用于所有操作的参数,它们只是可以轻松重用的全局定义。
参数依赖项
OpenAPI 3.0 不支持参数依赖关系和互斥参数。在 https://github.com/OAI/OpenAPI-Specification/issues/256 上有一个开放的功能请求。您可以做的就是在参数描述中记录限制,并在 400 Bad Request 响应中定义逻辑。例如,考虑接受相对日期范围(rdate
)或确切范围(start_date
+end_date
)的 /report
端点:
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 schema:8 type: string9 description: >10 A relative date range for the report, such as `Today` or `LastWeek`.11 For an exact range, use `start_date` and `end_date` instead.12 - name: start_date13 in: query14 schema:15 type: string16 format: date17 description: >18 The start date for the report. Must be used together with `end_date`.19 This parameter is incompatible with `rdate`.20 - name: end_date21 in: query22 schema:23 type: string24 format: date25 description: >26 The end date for the report. Must be used together with `start_date`.27 This parameter is incompatible with `rdate`.28 responses:29 "400":30 description: Either `rdate` or `start_date`+`end_date` are required.