我可以为响应组件Swagger定义一个扩展字段吗?



目前,我使用#/components/responses/Default response作为所有api定义的可重用属性。但有些API需要添加更多的字段,但不改变默认的响应格式。所以我可以重用默认响应并为响应添加更多字段吗

{
"openapi": "3.0.3",
"path": {
"/login": {
"post": {
"responses": {
200: {
"description": "Successful operation",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/responses/defaultResponse"
}
}
}
}
}
}
}
},
"components": {
"schemas" :{
"responseSchema": {
"type": "object",
"properties": {
"httpCode": { "type": "integer" },
"message": { "type": "string" }
}
}
},
"responses": {
"defaultResponse": { "$ref": "#/components/schemas/responseSchema" }
}
}
}

以上是我的swagger规范,但是对于Login,如果成功,我想要添加更多字段(token)来为客户端返回token,我可以这样做还是必须手动定义模式?

OpenAPI版本3中,您可以使用allOf关键字完成此操作。详细文档

{
"openapi": "3.0.3",
"info": {
"title": "Example",
"version": "1.0"
},
"paths": {
"/login": {
"post": {
"responses": {
"200": {
"description": "Successful operation",
"content": {
"application/json": {
"schema": {
"allOf": [
{
"$ref": "#/components/responses/defaultResponse"
},
{
"type": "object",
"properties": {
"token": {
"type": "string"
}
}
}
]
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"responseSchema": {
"type": "object",
"properties": {
"httpCode": {
"type": "integer"
},
"message": {
"type": "string"
}
}
}
},
"responses": {
"defaultResponse": {
"$ref": "#/components/schemas/responseSchema"
}
}
}
}

最新更新