如何为`map` 对象中的属性名称编写 OpenAPI 3 (Swagger) 规范?

use*_*081 11 swagger swagger-editor openapi

我试图描述的 API 有一个结构,其中根对象可以包含任意数量的子对象(属性本身就是对象)。“键”或根对象中的属性是子对象的唯一标识符,值是子对象的其余数据。

{
  "child1": { ... bunch of stuff ... },
  "child2": { ... bunch of stuff ... },
  ...
}
Run Code Online (Sandbox Code Playgroud)

这可以类似地建模为数组,例如:

[
  { "id": "child1", ... bunch of stuff ... },
  { "id": "child2", ... bunch of stuff ... },
  ...
]
Run Code Online (Sandbox Code Playgroud)

但这既使识别属性在结构上变得不太清楚,并使子代 ID 之间的唯一性隐式而非显式,因此我们想要使用对象或映射。

我已经看过Model with Map/Dictionary Properties的 Swagger 文档,但这并不完全适合我的用例。写一些类似的东西:

"Parent": {
  "additionalProperties": {
    "$ref": "#/components/schemas/Child",
  }
Run Code Online (Sandbox Code Playgroud)

产生这样的东西:

API 的 Swagger 渲染

这充分传达了属性中值的描述性,但我如何记录对象中“键”的限制?理想情况下,我想说“这不仅仅是任意字符串,而是与孩子对应的 ID”。这是否以任何方式支持?

Hel*_*len 14

你的例子是正确的。

我如何记录对象中“键”的限制?理想情况下,我想说“这不仅仅是任意字符串,而是与孩子对应的 ID”。这是否以任何方式支持?

开放API 3.1

OAS 3.1 完全支持 JSON Schema 2020-12,包括patternProperties. 此关键字允许您使用正则表达式定义字典键的格式:

"Parent": {
  "type": "object",
  "patternProperties": {
    "^child\d+$": {
      "$ref": "#/components/schemas/Child"
    }
  },
  "description": "A map of `Child` schemas, where the keys are IDs that correspond to the child"
}
Run Code Online (Sandbox Code Playgroud)

或者,如果属性名称由枚举propertyNames定义,则可以使用来定义该枚举:

"Parent": {
  "type": "object",
  "propertyNames": {
    "enum": ["foo", "bar"]
  },
  "additionalProperties": {
    "$ref": "#/components/schemas/Child"
  }
}
Run Code Online (Sandbox Code Playgroud)

OpenAPI 3.0 和 2.0

OpenAPI 假定密钥是字符串,但目前(从 OpenAPI 3.0 开始)无法限制密钥的内容/格式。您可以在模式中口头记录任何限制和细节description。添加模式示例可以帮助说明您的字典/地图可能是什么样子。

"Parent": {
  "type": "object",
  "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 ... },
  }
Run Code Online (Sandbox Code Playgroud)
如果已知可能的键名(例如,它们是枚举的一部分),您可以将字典定义为常规对象,将键定义为单个对象属性:
// Keys can be: key1, key2, key3

"Parent": {
   "type": "object",
   "properties": { 
      "key1": { "$ref": "#/components/schemas/Child" },
      "key2": { "$ref": "#/components/schemas/Child" },
      "key3": { "$ref": "#/components/schemas/Child" }
   }
}
Run Code Online (Sandbox Code Playgroud)

然后您可以添加"additionalProperties": false以真正确保仅使用这些密钥。