18

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.

Jean-Rémy Revy
  • 5,607
  • 3
  • 39
  • 65
fastcodejava
  • 39,895
  • 28
  • 133
  • 186

3 Answers3

32

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/

Helen
  • 87,344
  • 17
  • 243
  • 314
Evan Torkos
  • 376
  • 4
  • 5
6

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

Jason Desrosiers
  • 22,479
  • 5
  • 47
  • 53
  • 8
    This answer is outdated - `oneOf` is now supported in OpenAPI 3.0, as explained in [Evan Torkos' answer](https://stackoverflow.com/a/44534699/113116). – Helen Aug 30 '18 at 10:35
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

Dattatray
  • 1,745
  • 1
  • 21
  • 49