Search code examples
jsonapiswaggerswagger-2.0

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?


Solution

  • 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.