How to specify a property as null or a reference? discusses how to specify a property as null or a reference using jsonschema.
I'm looking to do the same thing with swagger.
To recap the answer to the above, with jsonschema, one could do this:
{
"definitions": {
"Foo": {
# some complex object
}
},
"type": "object",
"properties": {
"foo": {
"oneOf": [
{"$ref": "#/definitions/Foo"},
{"type": "null"}
]
}
}
}
The key point to the answer was the use of oneOf
.
The key points to my question:
I have a complex object which I want to keep DRY so I put it in a definitions section for reuse throughout my swagger spec: values of other properties; response objects, etc.
In various places in my spec a property may be a reference to such an object OR be null.
How do I specify this with Swagger which doesn't support oneOf
or
anyOf
?
Note: some swagger implementations use x-nullable
(or some-such) to specify a property value can be null, however, $ref
replaces the object with what it references, so it would appear any use of x-nullable
is ignored.
Not easy to do that. Even almost impossible. Your options :
Wait
There is a very long discussion about this point, maybe one day it will be done...
Use vendors extensions
You can use vendors extensions like x-oneOf and x-anyOf. I have already taken this hard way: You must to upgrade all used 'swagger tools' to take into account these vendors extensions.
In my case, we needed 'only' to :
It was a year ago, maybe now ...
Refactor your APIs
Many projects don't need anyOf and oneOf, why not us ?
In OpenAPI 3.0, you can use:
YAML version:
Wrapping
$ref
intoallOf
is needed to combine the$ref
with other keywords - because$ref
overwrites any sibling keywords. This is further discussed in the OpenAPI Specification repository: Reference objects don't combine well with “nullable”