5

I am defining an API and I have a field that is called "payload". We had this field defined as

"type": string

in our swagger however those payload data begun to have structure. More particular the client sends json objects as payload data that must obey in some rules. For example payload could be:

{
  "bark": true,
  "breed": "Dingo" 
}

if the payload is a Dog object or

{
  "hunts": true,
  "age": 13 
}

if it is a Cat object.

So in the yaml file I initially have:

payload:
        $ref: "#/definitions/payloaddata" 

and in the definitions area I have:

payloaddata:
    type: "object"
    schema: 
      oneOf: 
        - $ref: '#/components/schemas/Cat'
        - $ref: '#/components/schemas/Dog'

The components are defined as:

components:
  schemas:
    Dog:
      type: object
      properties:
        bark:
          type: boolean
        breed:
          type: string
          enum: [Dingo, Husky, Retriever, Shepherd]
    Cat:
      type: object
      properties:
        hunts:
          type: boolean
        age:
          type: integer

However the yaml file does not "compile" with this input. Any ideas how to do this?

cateof
  • 6,608
  • 25
  • 79
  • 153
  • Is your spec OpenAPI/Swagger 2.0 or OpenAPI 3.0? `oneOf` is only supported in 3.0. – Helen Sep 27 '17 at 11:34
  • added swagger: "3.0" at the top of the file. I am working at editor.swagger.io – cateof Sep 27 '17 at 11:36
  • Is it somehow possible to stay in 2.0 and allow an parameter to have multiple types as value? editor.swagger dot io does not support "3.0" – cateof Sep 27 '17 at 11:46
  • 1
    1) It's `openapi: 3.0.0`, not `swagger: '3.0'`. 2) No, 2.0 does not support multi-type values. – Helen Sep 27 '17 at 13:09
  • Thanks @Helen, you may answer the question if you like. This is the correct answer to move to openapi: 3.0 – cateof Sep 27 '17 at 15:27

2 Answers2

5

oneOf is supported in OpenAPI 3.0 but not in OpenAPI/Swagger 2.0. The code you posted is fine as long as your spec specifies openapi: 3.0.0 instead of swagger: '2.0'. You may also need to change some other things in your spec, e.g. #/definitions/ -> #/components/schemas/... and such.

Helen
  • 87,344
  • 17
  • 243
  • 314
5

The accepted solution did not work for me: Independently of declaring openapi: 3.0.0, the model definition was not compiling.

This one, however, worked for me:

Definition:

  TestModel:
    type: object
    oneOf:
      - $ref: '#/components/schemas/Foo'
      - $ref: '#/components/schemas/Bar'

Model usage:

testmodel:
  $ref: '#/components/schemas/TestModel'

Hopefully, it's useful to someone else.

NotYanka
  • 507
  • 1
  • 6
  • 12
  • And if `type: object` doesn't work for you, try `type: string` instead. This would be the case for a oneOf of string and integer only. – BlakBat Jun 28 '23 at 09:48