oneOf in Swagger schema does not work

2020-02-13 08:11发布

问题:

I want to define PaymentMethod as below. Is oneOf supported in swagger.yaml?

PaymentMethod:
      oneOf:
        - $ref: '#/definitions/NewPaymentMethod'
        - $ref: '#/definitions/ExistPaymentMethod'

The ExistPaymentMethod will have just id, and cardNumber where NewPaymentMethod will have no id, but all other details, e.g. cardNumber, cardholderName, cardholderAddress etc.

回答1:

oneOf is supported in OpenAPI version 3 (openapi: 3.0.0), but not in Swagger version 2 (swagger: '2.0').

PaymentMethod:
  oneOf:
    - $ref: '#/components/schemas/NewPaymentMethod'
    - $ref: '#/components/schemas/ExistPaymentMethod'

GitHub issue ref: https://github.com/OAI/OpenAPI-Specification/issues/333

For a list of changes in OpenAPI 3.0 compared to 2.0, see: https://blog.readme.io/an-example-filled-guide-to-swagger-3-2/



回答2:

What Swagger uses is only inspired by JSON Schema. They haven't deviated too much from JSON Schema, but they leave some things out, add some things, and change some behaviors. One of the things Swagger leaves out is oneOf.

More details can be found at http://swagger.io/specification/#schemaObject



回答3:

OneOf, anyOf and other similar directives are not supported swagger 2.0, but supported in Open API 3.0 specifications.

You will need to convert your Swagger 2.0 file to Open API 3.0 file.

Here is the link - https://blog.runscope.com/posts/tutorial-upgrading-swagger-2-api-definition-to-openapi-3

Here is one more useful link - https://github.com/swagger-api/swagger-ui/issues/3803