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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With