How to Limit My Swagger Definition Array to Be Either 0 or 3

I have my swagger definition like :

someDef:
    type: object
    properties:
      enable:
        type: boolean
        default: false
      nodes:
        type: array
        maxItems: 3
        items:
          type: object
          properties:
            ip:
              type: string
              default: ''

My nodes are array and it has maxitems: 3. I want my nodes items length to be either 0 or 3. Thanks in advance.

1 Answer

"Either 0 or 3 items" can be defined in OpenAPI 3.x (openapi: 3.x.x) but not in OpenAPI 2.0 (swagger: '2.0').

OpenAPI 3.x

You can use oneOf in combination with minItems and maxItems to define the "either 0 or 3 items" condition:

# openapi: 3.0.0

nodes:
  type: array
  items:
    type: object
    properties:
      ip:
        type: string
        default: ''
  oneOf:
    - minItems: 0
      maxItems: 0
    - minItems: 3
      maxItems: 3

Note while oneOf is part of the OpenAPI 3.0 Specification (i.e. you can write API definitions that include oneOf), actual tooling support for oneOf may vary.

OpenAPI 2.0

OAS 2 does not have a way to define "either 0 or 3 items". The most you can do is to use maxItems: 3 to define the upper limit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest