如何在 OpenAPI (Swagger) 中为相同的 HTTP 状态代码定义不同的响应?

How to define different responses for same HTTP status code in OpenAPI (Swagger)?

我正在为现有 API 编写 OpenAPI 规范。此 API returns 状态 200 表示成功和失败,但具有不同的响应结构。

例如,在注册 API 中,如果用户注册成功,API 会发送状态 200,其中 JSON:

{
    "result": true,
    "token": RANDOM_STRING
}

如果有重复的用户,API 也会发送状态 200,但带有以下 JSON:

{
    "result": false,
    "errorCode": "00002", // this code is duplicated error
    "errorMsg": "duplicated account already exist"
}

在这种情况下,如何定义响应?

这在 OpenAPI 3.0 中是可能的,但在 2.0 中是不可能的。

OpenAPI 3.0 支持 oneOf 指定响应的备用模式。您还可以添加多个响应 examples,例如成功和失败的响应。 Swagger UI 自 v.3.23.0.

起支持多个 examples
openapi: 3.0.0
...

paths:
  /something:
    get:
      responses:
        '200':
          description: Result
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: '#/components/schemas/ApiResultOk'
                  - $ref: '#/components/schemas/ApiResultError'
              examples:
                success:
                  summary: Example of a successful response
                  value:
                    result: true
                    token: abcde12345
                error:
                  summary: Example of an error response
                  value:
                    result: false
                    errorCode: "00002"
                    errorMsg: "duplicated account already exist"

components:
  schemas:
    ApiResultOk:
      type: object
      properties:
        result:
          type: boolean
          enum: [true]
        token:
          type: string
      required:
        - result
        - token
    ApiResultError:
      type: object
      properties:
        result:
          type: boolean
          enum: [false]
        errorCode:
          type: string
          example: "00002"
        errorMsg:
          type: string
          example: "duplicated account already exist"

在 OpenAPI/Swagger 2.0 中,每个响应代码只能使用一个模式,因此您最多可以将不同的字段定义为可选字段,并在模型中记录它们的用法 description 或操作 description.

swagger: "2.0"
...

definitions:
  ApiResult:
    type: object
    properties:
      result:
        type: boolean
      token:
        type: string
      errorCode:
        type: string
      errorMsg:
        type: string
    required:
      - result