How to write OpenAPI 3 (Swagger) specification for property name in `map` object?

大憨熊 提交于 2019-11-27 09:33:28

Your example is correct.

how do I document what the restrictions are for the "key" in the object? Ideally I'd like to say something like "it's not just any arbitrary string, it's the ID that corresponds to the child". Is this supported in any way?

OpenAPI assumes that the keys are strings, but there's currently (as of OpenAPI 3.0) no way to limit the contents/format of keys. You can document any restrictions and specifics verbally in the schema description. Adding schema examples could help illustrate what your dictionary/map might look like.

"Parent": {
  "additionalProperties": {
    "$ref": "#/components/schemas/Child"
  },
  "description": "A map of `Child` schemas, where the keys are IDs that correspond to the child",
  "example": {
    "child1": { ... bunch of stuff ... },
    "child2": { ... bunch of stuff ... },
  }

There's a proposal to add support for patternProperties in schemas, which would allow defining the key format. But as of OpenAPI 3.0.2, it's still in proposal stage.


If the possible key names are known (for example, they are part of an enum), you can define your dictionary as a regular object and the keys as individual object properties:

// Keys can be: key1, key2, key3

"Parent": {
  "key1": { "$ref": "#/components/schemas/Child" },
  "key2": { "$ref": "#/components/schemas/Child" },
  "key3": { "$ref": "#/components/schemas/Child" }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!