余晖落尽暮晚霞,黄昏迟暮远山寻
本站
当前位置:网站首页 > 编程知识 > 正文

OpenAPI规范(6)—描述参数

xiyangw 2023-10-03 16:20 20 浏览 0 评论

在OpenAPI 3.0中,参数在操作或路径的parameters分段中定义。若要描述一个参数,你需要指定它的名称(name)、位置(in)、数据类型(由schema或content定义)和其他属性(例如:description或required)。下面是一个示例:

paths:
 /users/{userId}:
 get:
 summary: Get a user by ID
 parameters:
 - in: path
 name: userId
 schema:
 type: integer
 required: true
 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可以包含多个路径参数,每个参数用花括号{ }表示。

GET /users/{id}
GET /cars/{carId}/drivers/{driverId}
GET /report.{format}

当客户端进行API调用时,每个路径参数都必须用实际值替换。在OpenAPI中,使用in: path来定义路径参数。参数名称必须与路径中指定的名称相同。还要记得添加required: true,因为路径参数总是必要的。例如,/users/{id}端点可以描述如下:

paths:
 /users/{id}:
 get:
 parameters:
 - in: path
 name: id # Note the name is the same as in the path
 required: true
 schema:
 type: integer
 minimum: 1
 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对通过(&)符号进行分隔。查询参数可以是必需的和可选的。

GET /pets/findByStatus?status=available
GET /notes?offset=100&limit=50

使用in: query来表示查询参数:

 parameters:
 - in: query
 name: offset
 schema:
 type: integer
 description: The number of items to skip before starting to collect the result set
 - in: query
 name: limit
 schema:
 type: integer
 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定义了一组保留字符:/?#[]@!amp;'()*+,;=,这些字符可以用作URI分量的分隔符。当这些字符需要在查询参数值中按照字面使用时,它们通常是经过百分号编码的。例如,/被编码成%2F(或%2f)。因此,参数值quotes/h2g2.txt将会被发送成:

GET /file?path=quotes%2Fh2g2.txt

如果你想要使某个查询参数不经过百分号编码,那么就要在参数定义中添加allowReserved: true:

 parameters:
 - in: query
 name: path
 required: true
 schema:
 type: string
 allowReserved: true # <-----

在这种情况下,参数值的发送方式,如下所示:

GET /file?path=quotes/h2g2.txt

标头参数

API调用可能要求使用HTTP请求来发送自定义标头。OpenAPI使得你能够将自定义的请求标头定义成in: header参数。例如,假设调用GET /ping需要X-Request-ID标头:

GET /ping HTTP/1.1
Host: example.com
X-Request-ID: 77e1c83b-7bb0-437b-bc50-a7a58e5660ac

使用OpenAPI 3.0,你可以将这个操作定义成:

paths:
 /ping:
 get:
 summary: Checks if the server is alive
 parameters:
 - in: header
 name: X-Request-ID
 schema:
 type: string
 format: uuid
 required: true

以类似的方式,你可以定义自定义的响应标头。标头参数可以是原始类型、数组和对象。数组和对象可以使用simple方式进行序列化。若要了解更多信息,请参考“参数序列化”。注意:不能使用名为Accepted、Content-Type和Authorization的标头参数。若要描述这些标头,请使用相应的OpenAPI关键字:

Cookie参数

操作还可以传递Cookie标头中的参数,例如:Cookie: name=value。可以在同一标头中发送多个cookie参数,以分号和空格作为分隔符。

GET /api/users
Host: example.com
Cookie: debug=0; csrftoken=BUSe35dohU3O1MZvDCUOJ

使用in: cookie来定义cookie参数:

 parameters:
 - in: cookie
 name: debug
 schema:
 type: integer
 enum: [0, 1]
 default: 0
 - in: cookie
 name: csrftoken
 schema:
 type: string

Cookie参数可以是原始值、数组和对象。数组和对象可以使用form方式进行序列化。若要了解更多信息,请参考“参数序列化”。注意:若要定义cookie身份验证,请改用API密钥。

必要参数和可选参数

在默认情况下,OpenAPI将所有请求参数都视为可选参数。你可以添加required: true,将参数标记成必需的。注意,路径参数必须带有required: true,因为它们总是必需的。

 parameters:
 - in: path
 name: userId
 schema:
 type: integer
 required: true # <----------
 description: Numeric ID of the user to get.

模式和内容

若要描述参数内容,你既可以使用schema关键字,也可以使用content关键字。它们是互斥的,可用于不同的场景。在大多数情况下,你将会使用schema关键字。它使得你能够描述原始值,以及序列化成字符串的简单数组和对象。数组和对象参数的序列化方法由该参数中使用的style关键字和explode关键字所定义。

parameters:
 - in: query
 name: color
 schema:
 type: array
 items:
 type: string
 # Serialize as color=blue,black,brown (default)
 style: form
 explode: false

在style和explode关键字不能覆盖到的复杂的序列化场景中,需要使用content关键字。例如,如果你需要在查询字符串中发送JSON字符串,如下所示:

filter={"type":"t-shirt","color":"blue"}

在这种情况下,你需要将参数模式包装成content/<media-type>,如下文所示。schema关键字定义了参数的数据结构和媒体类型(在这个示例中 — application/json),用作对描述序列化格式的外部规范的引用。

parameters:
 - in: query
 name: filter
?
 # Wrap 'schema' into 'content.<media-type>'
 content:
 application/json: # <---- media type indicates how to serialize / deserialize the parameter content
 schema:
 type: object
 properties:
 type:
 type: string
 color:
 type: string

默认参数值

在参数模式中使用default关键字指定可选参数的默认值。如果客户端没有在请求中提供参数值,那么服务端便会使用默认值作为参数值。默认值的类型必须和参数的数据类型相同。一个典型的例子是分页参数(例如:offset和limit):

GET /users
GET /users?offset=30&limit=10

假设offset的默认值是0,limit的默认值是20,范围是从0到100,那么这些参数的定义将如下所示:

 parameters:
 - in: query
 name: offset
 schema:
 type: integer
 minimum: 0
 default: 0
 required: false
 description: The number of items to skip before starting to collect the result set.
 - in: query
 name: limit
 schema:
 type: integer
 minimum: 1
 maximum: 100
 default: 20
 required: false
 description: The number of items to return.

常见错误

当使用default关键字时,可能会发生两个常见错误:

  • 带有required关键字的参数或属性使用default关键字(例如:路径参数)。这是没有意义的 — 如果某个值是必需的,那么客户端就必须总是发送它,并且永远不会使用默认值。
  • 使用default关键字来指定样本值。这不是默认值的用途,可能会导致某些Swagger工具出现不可预知的行为。请使用example或examples关键字来实现这种功能(请参考“添加示例”)。

枚举参数

通过将enum添加到参数的schema中,你便可以将参数限制在一个固定的取值范围之内。枚举值必须和参数的数据类型具有相同的类型。

 parameters:
 - in: query
 name: status
 schema:
 type: string
 enum:
 - available
 - pending
 - sold

更多信息:定义枚举值。

常量参数

你可以将常量参数定义成只有一个可能值的必需参数:

 parameters:
 - in: query
 name: rel_date
 required: true
 schema:
 type: string
 enum:
 - now

使用enum属性指定可能的值。在这个示例中,只能使用一个值,并且这将是Swagger UI中可供用户选择的唯一值。注意:常量参数和默认参数值是不同的。常量参数总是由客户端发送的,而默认值是服务端在客户端没有发送参数时使用的值。

空值和可空参数

查询字符串参数可能只有名称而没有值,如下所示:

GET /foo?metadata

使用allowEmptyValue关键字来描述这样的参数:

 parameters:
 - in: query
 name: metadata
 schema:
 type: boolean
 allowEmptyValue: true # <-----

OpenAPI 3.0还支持模式中的nullable关键字,允许操作参数具有null值。例如,以下模式对应于C#的int?和Java的java.lang.Integer。

 schema:
 type: integer
 format: int32
 nullable: true

注意:nullable和可选参数或空值参数是不同的。nullable意味着参数值可以是null。具体实现可以选择将缺少或空值的参数映射成null,但是严格说来,这些参数不是同一个东西。

参数示例

你可以为参数指定一个example关键字或多个examples关键字。示例的值应该匹配参数模式。单个示例:

 parameters:
 - in: query
 name: limit
 schema:
 type: integer
 minimum: 1
 example: 20

多个具有名称的示例:

 parameters:
 - in: query
 name: ids
 description: One or more IDs
 required: true
 schema:
 type: array
 items:
 type: integer
 style: form
 explode: false
 examples:
 oneId:
 summary: Example of a single ID
 value: [5] # ?ids=5
 multipleIds:
 summary: Example of multiple IDs
 value: [1, 5, 7] # ?ids=1,5,7

若要了解详细信息,请参考“添加示例”。

已废弃参数

使用deprecated: true来将一个参数标记成已废弃的。

 - in: query
 name: format
 required: true
 schema:
 type: string
 enum: [json, xml, yaml]
 deprecated: true
 description: Deprecated, use the appropriate `Accept` header instead.

通用参数

路径所有方法的通用参数

路径的所有操作共享的参数可以在路径级别上定义,而不是在操作级别上定义。该路径的所有操作都会集成路径级别的参数。有个典型的用例就是GET/PUT/PATCH/DELETE操作,它们能够操纵通过路径参数访问的资源。

paths:
 /user/{id}:
 parameters:
 - in: path
 name: id
 schema:
 type: integer
 required: true
 description: The user ID
 get:
 summary: Gets a user by ID
 ...
 patch:
 summary: Updates an existing user with the specified ID
 ...
 delete:
 summary: Deletes the user with the specified ID
 ...

在操作级别定义的任何额外的参数与路径级别的参数一起使用:

paths:
 /users/{id}:
 parameters:
 - in: path
 name: id
 schema:
 type: integer
 required: true
 description: The user ID.
 # GET/users/{id}?metadata=true
 get:
 summary: Gets a user by ID
 # Note we only define the query parameter, because the {id} is defined at the path level.
 parameters:
 - in: query
 name: metadata
 schema:
 type: boolean
 required: false
 description: If true, the endpoint returns only the user metadata.
 responses:
 '200':
 description: OK

可以在操作级别覆盖特定的路径级别的参数,但是不能删除。

paths:
 /users/{id}:
 parameters:
 - in: path
 name: id
 schema:
 type: integer
 required: true
 description: The user ID.
 # DELETE /users/{id} - uses a single ID.
 # Reuses the {id} parameter definition from the path level.
 delete:
 summary: Deletes the user with the specified ID.
 responses:
 '204':
 description: User was deleted.
 # GET /users/id1,id2,id3 - uses one or more user IDs.
 # Overrides the path-level {id} parameter.
 get:
 summary: Gets one or more users by ID.
 parameters:
 - in: path
 name: id
 required: true
 description: A comma-separated list of user IDs.
 schema:
 type: array
 items:
 type: integer
 minItems: 1
 explode: false
 style: simple
 responses:
 '200':
 description: OK

各种路径的通用参数

不同的API路径可能具有通用的参数,例如:分页参数。你可以在全局的components分段的参数下定义通用参数,并且通过$ref在其他地方引用它们。

components:
 parameters:
 offsetParam: # <-- Arbitrary name for the definition that will be used to refer to it.
 # Not necessarily the same as the parameter name.
 in: query
 name: offset
 required: false
 schema:
 type: integer
 minimum: 0
 description: The number of items to skip before starting to collect the result set.
 limitParam:
 in: query
 name: limit
 required: false
 schema:
 type: integer
 minimum: 1
 maximum: 50
 default: 20
 description: The numbers of items to return.
paths:
 /users:
 get:
 summary: Gets a list of users.
 parameters:
 - $ref: '#/components/parameters/offsetParam'
 - $ref: '#/components/parameters/limitParam'
 responses:
 '200':
 description: OK
 /teams:
 get:
 summary: Gets a list of teams.
 parameters:
 - $ref: '#/components/parameters/offsetParam'
 - $ref: '#/components/parameters/limitParam'
 responses:
 '200':
 description: OK

注意,components中定义的参数不是应用于所有操作的参数 — 它们只是简单的全局定义,可以轻松地重用。

参数依赖

OpenAPI 3.0不支持参数依赖性和互斥参数。有一个开放性的功能请求,位于:https://github.com/OAI/OpenAPI-Specification/issues/256。你可以做的是记录参数描述中的限制,并且在400 Bad Request响应中定义逻辑。例如,考虑/report端点,它会接受一个相对的日期范围(rdate)或一个确切的日期范围(start_date+end_date):

GET /report?rdate=Today
GET /report?start_date=2016-11-15&end_date=2016-11-20

你可以按照如下方式描述这个端点:

paths:
 /report:
 get:
 parameters:
 - name: rdate
 in: query
 schema:
 type: string
 description: >
 A relative date range for the report, such as `Today` or `LastWeek`.
 For an exact range, use `start_date` and `end_date` instead.
 - name: start_date
 in: query
 schema:
 type: string
 format: date
 description: >
 The start date for the report. Must be used together with `end_date`.
 This parameter is incompatible with `rdate`.
 - name: end_date
 in: query
 schema:
 type: string
 format: date
 description: >
 The end date for the report. Must be used together with `start_date`.
 This parameter is incompatible with `rdate`.
 responses:
 '400':
 description: Either `rdate` or `start_date`+`end_date` are required.

参考资料

  • 参数对象

相关推荐

华为交换机配置命令总结

1、配置文件相关命令[Quidway]displaycurrent-configuration显示当前生效的配置[Quidway]displaysaved-configuration显示fla...

解决账户无法登录的故障
解决账户无法登录的故障

在优化系统时错误地根据网上的提示,将唯一的Administrator账户设置为禁用,导致重启后无法进入系统。类似的故障还有使用组策略限制本地账户登录,导致重启后...

2023-10-11 17:16 xiyangw

S5720交换机登录提示初始密码存在安全风险
S5720交换机登录提示初始密码存在安全风险

问题描述客户每次登录输密码时,提示初始密码不安全,现在客户嫌麻烦想要去掉:Username:huaweiPassword:Warning:Theinitia...

2023-10-11 17:15 xiyangw

Springboot,Mybatis修改登录用户的密码
Springboot,Mybatis修改登录用户的密码

一、Mybatis.xml<updateid="changePassword"parameterType="string...

2023-10-11 17:15 xiyangw

PHP理论知识之沐浴更衣重看PHP基础(二)
PHP理论知识之沐浴更衣重看PHP基础(二)

接上篇,咱们继续讲解PHP基础八、标准PHP组件和框架的数量很多,随之产生的问题就是:单独开发的框架没有考虑到与其他框架的通信。这样对开发者和框架本身都是不利的...

2023-10-11 17:15 xiyangw

新鲜出炉UCloud云主机“数据方舟”评测报告(5)— — 关其城
新鲜出炉UCloud云主机“数据方舟”评测报告(5)— — 关其城

2015年10月29日,UCloud云主机黑科技——“数据方舟”功能正式上线,首轮内测随即开放。截止至2015年12月6日,我们共收到了534位用户的评测申...

2023-10-11 17:14 xiyangw

业余无线电Q简语及英文缩语
业余无线电Q简语及英文缩语

Q简语:语音通信及CW通信通用(加粗为常用)QRA电台何台QRB电台间之距离QRG告之正确频率QRH频率是否变动QRI发送音调QRJ能否收到QRK信号之可...

2023-10-11 17:14 xiyangw

非常详细!如何理解表格存储的多版本、生命周期和有效版本偏差
非常详细!如何理解表格存储的多版本、生命周期和有效版本偏差

表格存储在8月份推出了容量型实例,直接支持了表级别最大版本号和生命周期,高性能实例也将会在9月中旬支持这两个特性。那么,最大版本号和生命周期以及特有的...

2023-10-11 17:14 xiyangw

H3C交换机恢复出厂和各种基本配置,这20个要点你知道吗?
H3C交换机恢复出厂和各种基本配置,这20个要点你知道吗?

私信“干货”二字,即可领取138G伺服与机器人专属及电控资料!H3C交换机不知道密码如何恢复出厂设置1、开机启动,Ctrl+B进入bootrom菜单,选择恢复出...

2023-10-11 17:13 xiyangw

在使用移动支付系统的时候如何保护信息安全?

移动支付的方式近年来不断被更新,使得Venmo(据嘉丰瑞德理财师了解,此为美国的“支付宝”)之类的支付方式已经可以某种意义上代替随身携带现金了。但是你必须防范那些第三方应用程序轻松地获取你的银行卡以及...

界面控件DevExpress WinForms MVVM入门指南——登录表单(下)

从本文档中,您将了解如何向应用程序添加登录表单。在本节教程中着重讨论了如何实现此任务,这基本上是附加应用程序功能的一部分。DevExpressUniversalSubscription官方最新版免...

linux基础命令(一)
linux基础命令(一)

为啥要学linux?您可能熟悉WindowsXP、Windows7、Windows10和MacOSX等操作系统。Linux就是这样一种强大的操...

2023-10-11 17:13 xiyangw

MySQL数据库密码忘记了,怎么办?

#头条创作挑战赛#MySQL数据库密码忘记了且没有其他可以修改账号密码的账户时怎么办呢?登录MySQL,密码输入错误/*密码错误,报如下错误*/[root@TESTDB~]#mysql-u...

MobaXterm忘记Session密码,如何查看已保存的密码
MobaXterm忘记Session密码,如何查看已保存的密码

MobaXterm工具登录过SSH终端后,如果存储了Session(存储后再连接ssh的时候只需要输入账号不需要输入密码就可以直接连接上ssh),则可以...

2023-10-11 17:12 xiyangw

华为交换机密码丢失修改方法
华为交换机密码丢失修改方法

华为S2300交换机找回密码设置一、目的交换机的console和telnet密码丢失,无法登录设备。交换机已进行过数据配置,要把密码恢复而数据配置不能丢失。二、...

2023-10-11 17:12 xiyangw

取消回复欢迎 发表评论: