4

How do I indicate that in my_object you can have property_1 or property_2, but not both?

my_object:
  type: object
  properties:
    property_1:
      type: string
    property_2:
      type: string
Andres
  • 10,561
  • 4
  • 45
  • 63
  • Are `property_1` and `property_2` the only properties in this object, or can it have other properties too? – Helen Apr 11 '19 at 07:52
  • @Helen, it has other properties too – Andres Apr 11 '19 at 08:16
  • Are `property1`/`property2` required (i.e. one or the other MUST be present) or are they optional (i.e. one or the other MAY be present)? Are there required properties among other properties? – Helen Apr 11 '19 at 08:31
  • @Helen, at least one of them must be present. – Andres Apr 11 '19 at 10:22
  • Related: [How to define mutually exclusive query parameters in Swagger (OpenAPI)?](https://stackoverflow.com/q/21134029/113116), [Swagger 2.0 - how to make “one or the other” parameter required?](https://stackoverflow.com/q/29708505/113116) – Helen Apr 11 '19 at 15:41

2 Answers2

3

You may want to switch to OpenAPI 3.0, which supports oneOf keyword to define mutually exclusive conditions:

here is an example :

 my_object:
 type: object
 properties:
   property_1:
     type: string
   property_2:
    type: integer
 oneOf:
- required: [property_1]
- required: [property_2]
Hasni Iheb
  • 282
  • 2
  • 12
2

In OpenAPI 3.0 (openapi: 3.0.0), you can use the oneOf keyword to define mutually exclusive conditions. This schema requires that either property_1 or property_2 be present, but not both:

my_object:
  type: object
  properties:
    property_1:
      type: string
    property_2:
      type: string
    property_3:
      type: string
  oneOf:
    - required: [property_1]
    - required: [property_2]

If at least one of these two properties must be present, use anyOf instead.

Note: While oneOf is part of the OpenAPI Specification (as in, you can write API definitions that include oneOf), actual tooling support for oneOf may vary and be limited.


If you use OpenAPI 2.0 (swagger: "2.0"), it does not support oneOf, so you can only document this condition verbally in the schema description or property descriptions.

Helen
  • 87,344
  • 17
  • 243
  • 314
  • This does not work at least in SwaggerHub: roles: type: object properties: specific: type: array items: $ref: '#/components/schemas/Role' fromProto: type: boolean default: true oneOf: - required: [specific] - required: [fromProto] [![Documentation results:][1]][1] [1]: https://i.stack.imgur.com/XGXyp.png – cvigo Sep 29 '20 at 10:38
  • @cvigo Open an issue here: https://github.com/swagger-api/swagger-ui/issues – Helen Sep 29 '20 at 19:07