首页 > 解决方案 > 如何在 OpenApi 中使用 OneOf 和两个类似的模式?

问题描述

我在 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,但不确定如何区分这两种模式。

感谢帮助。

标签: schemaopenapiopenapi-generator

解决方案


OpenAPI模式对象有一个名为的属性additionalProperties,它指定模式中未定义的属性是否允许在实例中使用(这些属性被忽略)。

的默认值additionalPropertiesistrue这将导致FooResponse并且BarResponse对您的实例有效。设置additionalPropertiesfalseonFooResponse应该可以解决问题。

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


推荐阅读