Swagger complex response model with dynamic key value hash maps

后端 未结 3 880
滥情空心
滥情空心 2020-12-14 08:17

I\'m struggling with the syntax of swagger to describe a response type. What I\'m trying to model is a hash map with dynamic keys and values. This is needed to allow a local

3条回答
  •  温柔的废话
    2020-12-14 08:53

    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

提交回复
热议问题