Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

How to use OneOf with two similiar schemas in OpenApi?

I have the following schema in 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'

So I have FooResponse and BarResponse. I am getting OneOf matches multiple schema error though I have different required items in FooResponse and BarResponse. It seems like openapi matches two schemas even if there are additional required items in one of the schema.

Is there a way to fix this? I want to use OneOf, but not sure how to differentiate these two schema.

Appreciate the help.

question from:https://stackoverflow.com/questions/65672227/how-to-use-oneof-with-two-similiar-schemas-in-openapi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The OpenAPI Schema Object has a property called additionalProperties that specifies if properties not defined in the schema are allowed anyway in the instances(those properties are ignored).

Default value for additionalProperties is true which will cause both FooResponse and BarResponse to be valid for your instances. Setting additionalProperties to false on FooResponse should solve the problem.

If you don't want to disallow additional properties you would have to introduce some kind of type property in both objects and use a Discriminator Object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...