【问题标题】:How to define different responses for same HTTP status code in OpenAPI (Swagger)?如何在 OpenAPI (Swagger) 中为相同的 HTTP 状态代码定义不同的响应?
【发布时间】:2018-05-06 22:36:03
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

  • 有什么具体原因您不针对不同的响应使用不同的响应代码?
  • 我正在为已经存在的 api 构建文档。我无法编辑 api,因为有很多 api,现在应用程序使用了 api。

标签: swagger openapi


【解决方案1】:

这在 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

【讨论】:

  • 这没有在 swaggerhub 和其他 swagger 文件渲染器中正确渲染。它没有在声明的特定响应代码中引用正确的模式。它只是显示一个空白响应,而不使用声明的架构,
  • @iamjoshua 目前 Swagger UI does notoneOfanyOf 模型生成示例,但您可以通过提供自定义 exampleexamples 来解决此问题 - 如我的回答.如果其他渲染器工具存在问题,请考虑向工具供应商提交错误报告。
猜你喜欢
  • 1970-01-01
  • 2017-03-22
  • 2022-08-21
  • 2021-04-01
  • 1970-01-01
  • 2017-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多