JSON 规范:
"responses": {
"200": {
"description": "Успешный ответ сервиса",
"schema": {
"$ref": "#/definitions/BaseResponse"
},
"examples": {
"application/json": {
"status": true,
"response": {
"$ref": "#/definitions/Product"
},
"errors": null
}
}
}
}
结果:
但是我需要:
{
"status": true,
"response": {
"ProductNumber": "number",
"Barcode": "number",
"Length": 12,
"Width": 34,
"Height": 423,
"Volume": 1232
}
},
"errors": null
}
如何将 $refs 用于自定义格式响应的示例数组?
这是一个典型的案例,但我找不到它的文档。感谢您的反馈。
最佳答案
内联示例不支持 $ref
- 示例必须是完整示例:
"responses": {
"200": {
"description": "Успешный ответ сервиса",
"schema": {
"$ref": "#/definitions/BaseResponse"
},
"examples": {
"application/json": {
"status": true,
"response": {
"ProductNumber": "number",
"Barcode": "number",
"Length": 12,
"Width": 34,
"Height": 423,
"Volume": 1232
},
"errors": null
}
}
}
}
而不是使用
responses.<code>.examples
,您可以在 BaseResponse
中指定示例值模式,Swagger UI 将使用它们。例如,您可以在
BaseResponse
中添加一个完整的示例。架构: "definitions": {
"BaseResponse": {
"type": "object",
"properties": {
"status": {
"type": "boolean"
},
...
},
"example": { // <------ schema-level example
"status": true,
"response": {
"ProductNumber": "number",
"Barcode": "number",
"Length": 12,
"Width": 34,
"Height": 423,
"Volume": 1232
},
"errors": null
}
}
}
或使用属性级示例:
"definitions": {
"BaseResponse": {
"type": "object",
"properties": {
"status": {
"type": "boolean",
"example": true // <------
},
"response": {
"$ref": "#/definitions/Product"
},
"errors": {
"example": null // <------
}
}
},
"Product": {
"type": "object",
"properties": {
"ProductNumber": {
"type": "string",
"example": "number" // <------
},
"Length": {
"type": "integer",
"example": 12 // <------
},
...
}
}
}
我要注意的是
"errors": null
和 "example": null
在 OpenAPI 2.0 (fka Swagger) 中实际上无效,因为它不支持可空类型。可空类型为 supported仅在 OpenAPI 3.0 中。
关于php - 如何将 ref 用于示例 Swagger?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47525254/