我正在编写一个 OpenAPI (Swagger) 定义,其中查询参数可以不带任何值或 N 个值,如下所示:
I am writing an OpenAPI (Swagger) definition where a query parameter can take none, or N values, like this:
/path?sort=field1,field2
如何在 OpenAPI YAML 中编写这个?
How can I write this in OpenAPI YAML?
我尝试了以下方法,但没有产生预期的结果:
I tried the following, but it does not produce the expected result:
- name: sort
in: query
schema:
type: string
enum: [field1,field2,field3]
allowEmptyValue: true
required: false
description: Sort the results by attributes. (See http://jsonapi.org/format/1.1/#fetching-sorting)
推荐答案
包含逗号分隔的值列表的查询参数被定义为数组.如果值是预定义的,那么它是一个枚举数组.
A query parameter containing a comma-separated list of values is defined as an array. If the values are predefined, then it's an array of enum.
默认情况下,数组可以有任意数量的项目,与您的无或更多"匹配.要求.如果需要,您可以使用 minItems
和 maxItems
限制项目数量,并可选择强制执行 uniqueItems: true
.
By default, an array may have any number of items, which matches your "none or more" requirement. If needed, you can restrict the number of items using minItems
and maxItems
, and optionally enforce uniqueItems: true
.
参数定义如下所示.collectionFormat: csv
表示值以逗号分隔,但这是默认格式,因此可以省略.
The parameter definition would look as follows. collectionFormat: csv
indicates that the values are comma-separated, but this is the default format so it can be omitted.
parameters:
- name: sort
in: query
type: array # <-----
items:
type: string
enum: [field1, field2, field3]
collectionFormat: csv # <-----
required: false
description: Sort the results by attributes. (See http://jsonapi.org/format/1.1/#fetching-sorting)
OpenAPI 3.x
OpenAPI 2.0 中的collectionFormat: csv
已替换为 style: form
+ explode: false
.style:form
是查询参数的默认样式,可以省略.
OpenAPI 3.x
collectionFormat: csv
from OpenAPI 2.0 has been replaced with style: form
+ explode: false
. style: form
is the default style for query parameters, so it can be omitted.
parameters:
- name: sort
in: query
schema:
type: array # <-----
items:
type: string
enum: [field1, field2, field3]
required: false
description: Sort the results by attributes. (See http://jsonapi.org/format/1.1/#fetching-sorting)
explode: false # <-----
我认为不需要 allowEmptyValue
,因为在这种情况下,空数组实际上是一个空值.此外,allowEmptyValue
不推荐 从 OpenAPI 3.0.2 开始使用,因为它将在未来的版本中删除."
I think there's no need for allowEmptyValue
, because an empty array will be effectively an empty value in this scenario. Moreover, allowEmptyValue
is not recommended for use since OpenAPI 3.0.2 "as it will be removed in a future version."
相关推荐
最新文章