Why `additionalProperties` is the way to represent Dictionary/Map in Swagger/OpenAPI 2.0

前端 未结 2 1715
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 03:07

Although I have seen the examples in the OpenAPI spec:

type: object
additionalProperties:
  $ref: \'#/definitions/ComplexModel\'
2条回答
  •  臣服心动
    2020-12-03 03:16

    First thing, I found a better explanation for additionalProperties:

    For an object, if this is given, in addition to the properties defined in properties all other property names are allowed. Their values must each match the schema object given here. If this is not given, no other properties than those defined in properties are allowed.

    So here is how I finally understood this:

    Using properties, we can define a known set of properties similar to Python's namedtuple, however if we wish to have something more like Python's dict, or any other hash/map where we can't specify how many keys there are nor what they are in advance, we should use additionalProperties.

    additionalProperties will match any property name (that will act as the dict's key, and the $ref or type will be the schema of the dict's value, and since there should not be more than one properties with the same name for every given object, we will get the enforcement of unique keys.

    Note that unlike Python's dict that accepts any immutable value as a key, since the keys here are in essence property names, they must be strings. (Thanks Ted Epstein for that clarification). This limitation can be tracked down to pair := string : value in the json specification.

提交回复
热议问题