How to specify an unknown number of a parameter in the response Open API

Viewed 625

I'm trying to model my API using swagger and the Open API 3.0 specification. I have made some schemas and now I'm modeling the response of my endpoints. The problem is that they return something like this:

[
 {
  "name": "this attribute is always here"
  "type1": { "description": "this maybe appear or not"  },
  "type2": { "description": "this maybe appear or not"  },
  ...
  "typeN": { "description": "N is not a fixed number, it may range from 0 to another positive integer"  },
 }
]

I know how to model the array and the object (with the name property). The problem comes when I have to model the typeX properties, I do not know how to specify that they are optional and the number of ocurrences is variable. Any idea?

1 Answers

This object is basically a string-to-object dictionary/hashmap with an extra name property. Fixed properties are defined in properties, and the dictionary part can be defined using either patternProperties (in OpenAPI 3.1) or additionalProperties (in OpenAPI 3.0 and 2.0).

OpenAPI 3.1

In OAS 3.1 your object can be defined as follows. Since the optional property names all follow the typeX format, the schema uses patternProperties to define the regex for the property names.

MyObject:
  type: object
  required: [name]
  properties:
    name:
      type: string
  patternProperties:  # <-- This part defines the "typeX" properties
    ^type\d+$:        # <-- Property name regex
      type: object    # <-- Property value
      properties:
        description:
          type: string
  additionalProperties: false  # No other properties other than "name" and "typeX"

OpenAPI 3.0 and 2.0

In earlier OAS versions, you use additionalProperties to define "may have extra properties with <such> values", but there's no way to define the format of those property names. You can however mention the property name format in the schema description and also add a schema example for documentation purposes.

MyObject:
  type: object
  description: >-
    In addition to the `name` property, this object may have an arbitrary
    number of properties named `typeX` where X is a positive integer.
  required: [name]
  properties:
    name:
      type: string
  additionalProperties:
    # This part defines the *value* of the typeX properties
    type: object
    properties:
      description:
        type: string

  # Optional schema example
  name: something
  type1:
    description: ....
  type2:
    description: ....
Related