如何使用 OpenAPI/Swagger 定义数组项的排除类型



Swagger 文档解释了如何定义包含混合类型的数组,例如 ["foo", 5, -2, "bar"] 。但是,我如何定义数组必须包含一种类型的项目(字符串,["foo", "bar"](或另一种类型的项目(整数,[5, -2](?

我已经尝试过这个,但是 Swagger UI 无法呈现它,所以我想这是错误的:

      oneOf:
        - items:
          - $ref: '#/components/schemas/SchemaA'
        - items:
          - $ref: '#/components/schemas/SchemaB'

首先,请记住,oneOf仅在OpenAPI 3.0(openapi: 3.0.0(中受支持,而在OpenAPI 2.0(swagger: '2.0'(中不受支持。

可以使用如下所示oneOf定义方案:

oneOf:
  - type: array
    items:
      type: string
  - type: array
    items:
      type: integer
  - type: array
    items:
      $ref: '#/components/schemas/SchemaA'

在vanilla JSON Schema中,type: array可以移出oneOf并放在oneOf旁边,但我不确定OpenAPI是否允许这样做(OpenAPI规范对此不清楚(。

type: array
oneOf:
  - items:
      type: string
  - items:
      type: integer
  - items:
      $ref: '#/components/schemas/SchemaA'


我已经试过了,但是 Swagger UI 无法呈现它

目前,Swagger UI 不会自动生成oneOfanyOf架构的示例(请参阅此问题(。解决方法是手动在oneOf旁边添加example

example: [1, 2, 3]  # <------
oneOf:
  - type: array
    items:
      type: string
  - type: array
    items:
      type: integer
  - type: array
    items:
      $ref: '#/components/schemas/SchemaA'

最新更新