龙空技术网

OpenAPI规范(6)—描述参数

水晶命匣 269

前言:

今天咱们对“openapi30”大体比较关怀,咱们都想要学习一些“openapi30”的相关知识。那么小编也在网上网罗了一些有关“openapi30””的相关内容,希望我们能喜欢,同学们快快来学习一下吧!

在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: Valuecookie参数,通过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=availableGET /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%20redpipeDelimited(相同于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将会被发送成:

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.1Host: example.comX-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/usersHost: example.comCookie: 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 /usersGET /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不支持参数依赖性和互斥参数。有一个开放性的功能请求,位于:。你可以做的是记录参数描述中的限制,并且在400 Bad Request响应中定义逻辑。例如,考虑/report端点,它会接受一个相对的日期范围(rdate)或一个确切的日期范围(start_date+end_date):

GET /report?rdate=TodayGET /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.
参考资料参数对象

标签: #openapi30