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

frebpwbc  于 2022-12-18  发布在  其他
关注(0)|答案(1)|浏览(115)

目前,我使用#/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" }
    }
  }
}

以上是我的昂首阔步的规格,但与登录,如果成功,我想把更多的字段(令牌)返回令牌的客户端,我可以这样做,或必须手动定义模式?

jhdbpxl9

jhdbpxl91#

OpenAPI版本3中,您可以使用allOf关键字执行此操作。Detail document

{
  "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"
      }
    }
  }
}

相关问题