Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

openapi - How to specify a property can be null or a reference with swagger

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:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

OpenAPI 3.1

Define the property as anyOf of the $ref and type: 'null'.

YAML version:

foo:
  anyOf:
    - type: 'null'   # Note the quotes around 'null'
    - $ref: '#/components/schemas/Foo'

JSON version:

"foo": {
    "anyOf": [
        { "type": "null" },
        { "$ref": "#/components/schemas/Foo" }
    ]
}

Why use anyOf and not oneOf? oneOf will fail validation if the referenced schema itself allows nulls, whereas allOf will work.

OpenAPI 3.0

YAML version:

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

JSON version:

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

In OAS 3.0, wrapping $ref into allOf 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”


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...