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

Web*_*per 6 swagger openapi

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

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

{
    "result": true,
    "token": RANDOM_STRING
}
Run Code Online (Sandbox Code Playgroud)

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

{
    "result": false,
    "errorCode": "00002", // this code is duplicated error
    "errorMsg": "duplicated account already exist"
}
Run Code Online (Sandbox Code Playgroud)

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

Hel*_*len 8

这在OpenAPI 3.0中是可能的,但在2.0中则不行.

OpenAPI 3.0支持oneOf为响应指定备用模式.您还可以添加多个响应examples,例如成功和失败的响应(但是,Swagger UI 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"
Run Code Online (Sandbox Code Playgroud)

在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
Run Code Online (Sandbox Code Playgroud)