Swagger complex response model with dynamic key value hash maps

Your usage of additionalProperties is correct and your model is correct.

additionalProperties

In Swagger/OpenAPI, hashmap keys are assumed to be strings, so the key type is not defined explicitly. additionalProperties define the type of hashmap values. So, this schema

type: object
additionalProperties: 
  type: string

defines a string-to-string map such as:

{
  "en": "English text",
  "de": "Deutscher Text"
}

If you needed a string-to-integer map such as:

{
  "en": 5,
  "de": 3
}

you would define additionalProperties as having value type integer:

type: object
additionalProperties: 
  type: integer

Required key in a hashmap

To define en as a required key in the hashmap:

type: object
properties:
  en:
    type: string
required: [en]
additionalProperties: 
  type: string

Complete example

definitions:
  delayReason:
    type: object
    properties:
      id:
        type: string
        description: Identifier for a delay reason.
      name:
        type: object
        description: A hashmap with language code as a key and the text as the value.
        properties:
          en:
            type: string
            description: English text of a delay reason.
        required: [en]
        additionalProperties: 
          type: string
    required: [id, name]
    example:
      id: '123' # Note the quotes to force the value as a string
      name: 
        en: English text
        de: Deutscher Text

There is also no clue in this that the result will have a language code as a key and the text as the value of the hash map.

Things like that can be documented verbally in the description.

the example also does not seem to work as expected. It generates an empty $folded: in the UI.

Not sure what the problem was with your original spec, but the spec above is valid and looks fine in the Swagger Editor.

Model schema in Swagger Editor

Leave a Comment