Swagger:从枚举中取一个或多个值

Swagger: take one or more values from enum

我正在编写一个 OpenAPI (Swagger) 定义,其中查询参数可以采用 none 或 N 个值,如下所示:

/path?sort=field1,field2

如何在 OpenAPI YAML 中编写此文件?

我尝试了以下方法,但没有产生预期的结果:

- 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)

包含逗号分隔的值列表 的查询参数定义为数组。如果值是预定义的,那么它是一个 枚举数组

默认情况下,数组可以包含任意数量的项目,这符合您的“none 或更多”要求。如果需要,您可以使用 minItemsmaxItems 限制项目数量,并可选择强制执行 uniqueItems: true.

OpenAPI 2.0

参数定义如下所示。 collectionFormat: csv 表示值以逗号分隔,但这是默认格式,因此可以省略。

      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: falsestyle: form是查询参数的默认样式,所以可以省略。

      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 起使用 not recommended,“因为它将在未来版本中删除。”