首页 > 解决方案 > 是否可以在 OAS v.3 中合并两个响应

问题描述

我想为我的端点获得另一个响应和一组对象的组合响应,如下例所示:

{
  access: "string",
  refresh: "string",
  "hospitals": [
    {
      "title": "a hospital",
      "base_url": "hospital.com",
      "secret_key": "68e656b251e67e8358bef8483ab0d51c6619f3e7a1a9f0e75838d41ff368f728"
    }
  ]
}

以下是我的令牌对响应,其中包括accessrefresh

responses:
    TokenPairResponse:
        description: generated token pair
        content:
            application/json:
                schema:
                    type: object
                    properties:
                      access:
                        type: string
     
                      refresh:
                        type: string

此外,要创建一系列医院:

description: user verified successfully
content:
    application/json:
        schema:
            type: object
            properties:
                hospitals:
                    type: array
                items:
                      $ref: "#/components/schemas/Hospital"

现在,我想知道是否有任何方法可以像上述示例一样在单个响应中组合array of hospitals和。TokenPairResponse

更新:我已将这些添加到回复中:

hospitals:
  description: array of hostpitals
  content:
    application/json:
      schema:
        type: object
        properties:
          hospitals:
            type: array
            items:
              $ref: "#/components/schemas/Hospital"

VerifyUser:
  description: repsonse of user successfull verfication
  content:
    application/json:
      schema:
        allOf:
          - $ref: "#/components/responses/hospitals"
          - $ref: "#/components/responses/TokenPairResponse"

我在我的路径中引用了它们,如下所示:

responses:
    200:
        description: user verified successfully
        $ref: "#/components/responses/VerifyUser"

这不会渲染,我得到:no example available

标签: swaggeropenapi

解决方案


allOf只能引用模式(ie #/components/schemas/...)但不能引用响应组件(#/components/responses/...)。

将您的响应模式移动到该components/schemas部分。然后你可以allOf像这样定义一个模式:

openapi: 3.0.0
...

components:
  schemas:
    VerifyUser:
      allOf:
        - $ref: "#/components/schemas/Hospitals"    # <---------
        - $ref: "#/components/schemas/TokenPair"    # <---------
    Hospital:
      type: object
      ...
    Hospitals:
      type: object
      properties:
        hospitals:
          type: array
          items:
            $ref: "#/components/schemas/Hospital"
    TokenPair:
      type: object
      properties:
        access:
          type: string
        refresh:
          type: string

  responses:
    hospitals:
      description: array of hostpitals
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Hospitals'
    VerifyUser:
      description: repsonse of user successfull verfication
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/VerifyUser'
    TokenPairResponse:
      description: generated token pair
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/TokenPair'

推荐阅读