How to specify a property can be null or a link with swagger

How to specify a property as null or as a reference? discusses how to specify a property as null or as a reference using jsonschema.

I am going to do the same with swagger.

To repeat the answer to the above, using jsonschema you can do the following:

{ "definitions": { "Foo": { # some complex object } }, "type": "object", "properties": { "foo": { "oneOf": [ {"$ref": "#/definitions/Foo"}, {"type": "null"} ] } } } 

The key point in the answer was the use of oneOf .

Key points of my question:

  1. I have a complex object that I want to keep DRY, so I put it in the definition section for reuse in my specification: the values ​​of other properties; response objects, etc.

  2. In different places in my specification, a property can be a reference to such an object OR be null.

How do I specify this with Swagger that does not support oneOf or anyOf ?

Note: some swagger implementations use x-nullable (or something like that) to indicate the value of the property, which may be null, however, $ref replaces the object with what it refers to, so any use of x-nullable may seem x-nullable ignored.

+6
source share
2 answers

It’s not easy to do this. Even almost impossible. Your options:

Wait

There is a very long discussion about this point , maybe one day it will be done ...

Use vendor extensions

You can use vendor extensions such as x-oneOf and x-anyOf. I have already made this difficult path: you must update all the tools used 'to take into account these supplier extensions.

In my case, we only needed to:

  • Develops native Jax-RS parser with custom annotations to extract swagger API file from sources
  • Extends swagger-codegen to accommodate these extensions for generating Java code for our customers.
  • Developing our own swagger-ui: to facilitate this work, we added a preprocessing step to convert our smagger scheme with our extensions into a valid json scheme. It is easier to find a module for representing json schemas than jargas schemas in javascript. By cons, we abandoned the idea of ​​testing the API using the try button.

That was a year ago, maybe now ...

Refactoring your APIs

Many projects don't need anyOf and oneOf, why not?

+2
source

In OpenAPI 3.0 you can use:

 "foo": { "nullable": true, "allOf": [ { "$ref": "#/definitions/Foo" } ] } 

YAML version:

 foo: nullable: true allOf: - $ref: '#/definitions/Foo' 

Wrapping $ref in allOf necessary to combine $ref with other keywords - because $ref overwrites any related keywords. This is further discussed in the OpenAPI specification repository: Reference objects do not fit well with nullable.

+7
source

All Articles