【问题标题】:How to use OneOf with two similiar schemas in OpenApi?如何在 OpenApi 中使用 OneOf 和两个类似的模式?
【发布时间】:2021-01-11 18:04:12
【问题描述】:

我在 openapi 中有以下架构

/submit:
post:
  description: Submit info
  x-openapi-router-controller: abc.def
  operationId: submit_info
  requestBody:
    description: Submit request
    required: true
    content:
      application/json:
        schema:
          $ref: '#/components/schemas/SubmitRequest'
  responses:
    200:
      description: submitted successfully
      content:
        application/json:
          schema:
            oneOf:
              - $ref: '#/components/schemas/FooResponse'
              - $ref: '#/components/schemas/BarResponse'
FooResponse:
  type: object
  required:
    - id
    - value
  properties:
    id:
      type: string
      description: id
      example: '1234'
    value:
      type: string
      description: value
      example: 'foo'
BarResponse:
  type: object
  required:
    - id
    - value
    - data
  properties:
    id:
      type: string
      description: id
      example: '1234'
    value:
      type: string
      description: value
      example: 'foo'
    data:
      type: object
      required:
        - transaction_id
      description: Data associated bar response
      properties:
        transaction_id:
          type: string
          description: transaction id
          example: 'c2345'

所以我有 FooResponse 和 BarResponse。尽管 FooResponse 和 BarResponse 中有不同的必需项,但我收到 OneOf 匹配多个模式错误。即使其中一个架构中有其他必需项,openapi 似乎也匹配两个架构。

有没有办法解决这个问题?我想使用 OneOf,但不确定如何区分这两种模式。

感谢您的帮助。

【问题讨论】:

    标签: schema openapi openapi-generator


    【解决方案1】:

    OpenAPI Schema Object 有一个名为 additionalProperties 的属性,它指定在实例中是否允许未在架构中定义的属性(这些属性被忽略)。

    additionalProperties 的默认值为true,这将导致FooResponse 和BarResponse 对您的实例都有效。 在FooResponse 上将additionalProperties 设置为false 应该可以解决问题。

    如果您不想禁止其他属性,则必须在两个对象中引入某种type 属性并使用Discriminator Object。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 2017-06-02
      • 2021-11-20
      • 1970-01-01
      • 2022-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多