Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow an object to have oneOf some types in swagger

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?

like image 800
cateof Avatar asked Sep 27 '17 11:09

cateof


2 Answers

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.

like image 136
Helen Avatar answered Sep 18 '22 02:09

Helen


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.

like image 37
NotYanka Avatar answered Sep 22 '22 02:09

NotYanka