How to write OpenAPI 3 (Swagger) specification for

2019-01-15 15:44发布

The API I'm trying to describe has a structure where the root object can contain an arbitrary number of child objects (properties that are themselves objects). The "key", or property in the root object, is the unique identifier of the child object, and the value is the rest of the child object's data.

{
  "child1": { ... bunch of stuff ... },
  "child2": { ... bunch of stuff ... },
  ...
}

This could similarly be modeled as an array, e.g.:

[
  { "id": "child1", ... bunch of stuff ... },
  { "id": "child2", ... bunch of stuff ... },
  ...
]

but this both makes it structurally less clear what the identifying property is and makes uniqueness among the children's ID implicit rather than explicit, so we want to use an object, or a map.

I've seen the Swagger documentation for Model with Map/Dictionary Properties, but that doesn't adequately suit my use case. Writing something like:

"Parent": {
  "additionalProperties": {
    "$ref": "#/components/schemas/Child",
  }

Yields something like this:

Swagger rendering of API

This adequately communicates the descriptiveness of the value in the property, but 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?

1条回答
Animai°情兽
2楼-- · 2019-01-15 16:15

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" }
}
查看更多
登录 后发表回答