1

I am new to OpenAPI-specifications and I was confused about the type of a variable when the attribute additionalProperties is used. For example at https://github.com/OAI/OpenAPI-Specification/blob/main/versions/2.0.md#schemaObject we see the example

{
  "type": "object",
  "additionalProperties": {
    "type": "string"
  }
}

What is the type of this now? Is it a string or an object? I do not see how it can be both of them. thanks in advance, Koen

1 Answers1

1

In this context, the additionalProperties keyword is used to define dictionaries/maps. type: object represents the dictionary itself, and the additionalProperties keyword defines the type of values in the dictionary. The key type is not mentioned because the keys are always strings.

A more general explanation is that additionalProperties is used to allow or deny extra properties not explicitly defined in the properties and patternProperties sections. If extra properties are allowed, additionalProperties specifies their value type.


The example is your post represents a simple string-to-string dictionary, or an object with arbitrary properties whose values are strings, such as:

{
  "foo": "bar",
  "hello": "world"
}

Similarly, a string-to-integer dictionary is defined as:

{
  "type": "object",
  "additionalProperties": {
    "type": "integer"
  }
}

This schema represents objects such as:

{
  "apples": 3,
  "oranges": 5
}

If the additionalProperties keyword does not specify a type, this means a free-form object with arbitrary properties and values.

{
  "type": "object",
  "additionalProperties": {}
}

// In OpenAPI 3.x, this can also be written as
{
  "type": "object",
  "additionalProperties": true
}

For additional info and examples, see:

Helen
  • 87,344
  • 17
  • 243
  • 314
  • I understand what you mean, but I wonder for what reason it is done. In the example, what is then the added value of setting the type to "object" if you set in additionalProperties that the type is integer? Why not just setting immediately that type = integer, setting type = "object" seems redundant and more complicated than necessary ? – koen ruymbeek Sep 07 '22 at 05:59
  • 1
    `additionalProperties` does not automatically enforce the object type on its parent schema, it means "_if the instance is an object_, then this constraint applies". That's why you need an explicit `type: object` to enforce the object type. Omitting `type: object` means that the instance can be not just an object, but also other data types - array, string, number, boolean, etc. See [this answer](https://stackoverflow.com/a/47390723/113116) for more details. – Helen Sep 07 '22 at 08:40