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
CodePudding user response:
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:
- Dictionaries, HashMaps and Associative Arrays on swagger.io
- Additional Properties in the Understanding JSON Schema guide
- Why
additionalProperties
is the way to represent Dictionary/Map in OpenAPI - Swagger Editor dictionary parameter definition
- Swagger complex response model with dynamic key value hash maps