Additionalproperties provide flexibility around API data not explicitly defined in your schema. Think of additionalproperties as the rules in an OpenAPI definition for handling unstructured data. Translated into code, additionalproperties become a dictionary, map, hashmap, or associative array, depending on the programming language.Three popular uses are
- Allow arbitrary data of varying types (string, boolean, integer, object, array)
- Allow only one specific type of arbitrary data (i.e. type: integer)
- Do not allow arbitrary data
Let’s start with a character schema for a fictitious Comic API.
Our response looks like this
We know that our API endpoint will consistently return an object with properties name and universe both of type string.
Our OpenAPI definition looks like this.
Allow Arbitrary Data of Varying Type
To allow the most flexibility for arbitrary data use
additionalProperties: true. Below, we add a meta property to hold arbitrary information about Thor.
Why do we need flexibility? We might want a different data structure for Archie Comics.
Our OpenAPI definition for both objects would be the same.
Allow Arbitrary Data of Specific Type
You can be more strict with the allowed type in your additional data. For example, we want only integers.
Our OpenAPI definition would look like this
Don’t Allow Arbitrary Data
Additionalproperties are allowed by default in OpenAPI. To enforce maximum strictness use
additionalProperties: false to block all arbitrary data.
Trying to POST the following would throw a validation error.
AdditionalProperties and Code Generation
How do additionalproperties translate into generated code? Below is how generated Java code might look (pseudo-code):
The exact behavior may vary based on the programming language and code-generation tool you are using. Always refer to the documentation of the specific tool or library for details on how it handles additionalproperties in generated code.
Additionalproperties should only be used where appropriate. Avoid creating schemas that are too flexible. Using additionalproperties to avoid documenting well-known properties should be considered an anti-pattern.
Looking to improve the quality of your OpenAPI definition? Try APIMatic's VSCode extension with over 1200 validation and linting rules.