You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在OpenAPI中针对不同失败原因定义各异的响应体类型?

在OpenAPI规范中记录不同失败原因的方法

针对你提出的场景——同一个400状态码下因不同参数错误返回不同结构的响应体,可以通过以下方式在OpenAPI中清晰记录:

1. 定义错误响应的Schema组件

首先在components/schemas下分别定义每种错误的结构,再通过oneOf组合成统一的参数错误Schema:

components:
  schemas:
    # 保留原有的DataType定义
    DataType:
      type: object
      properties:
        # 此处为原有DataType的属性定义
    
    # 定义foo参数错误的响应结构
    BadFooError:
      type: object
      properties:
        bad_foo_parameter:
          type: string
          description: foo参数错误的具体原因描述
      required: [bad_foo_parameter]
    
    # 定义bar参数错误的响应结构
    BadBarError:
      type: object
      properties:
        bad_bar_parameter:
          type: string
          description: bar参数错误的具体原因描述
      required: [bad_bar_parameter]
    
    # 组合两种错误类型,明确400响应的可能结构
    ParameterError:
      oneOf:
        - $ref: '#/components/schemas/BadFooError'
        - $ref: '#/components/schemas/BadBarError'

2. 配置400响应并添加示例

在接口的responses节点下,为400状态码绑定上述组合Schema,并添加对应错误的示例,直观展示不同失败场景的响应:

responses:
  '200':
    $ref: '#/components/schemas/DataType'
  '400':
    description: 参数错误,可能是foo参数或bar参数不符合要求
    content:
      application/json:
        schema:
          $ref: '#/components/schemas/ParameterError'
        examples:
          Foo参数错误:
            summary: 当foo参数传入有误时的响应
            value:
              bad_foo_parameter: "the underlying foo problem"
          Bar参数错误:
            summary: 当bar参数传入有误时的响应
            value:
              bad_bar_parameter: "the underlying bar problem"

补充说明

  • 使用oneOf可以明确限定400响应体只能是两种错误结构中的一种,比anyOf更严谨;
  • 如果你的错误响应中包含可用于区分类型的字段(比如error_code),还可以添加discriminator进一步强化类型区分逻辑;
  • 通过examples字段可以让开发者快速理解不同错误场景下的实际返回格式。

内容的提问来源于stack exchange,提问作者Ramón J Romero y Vigil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 14:06:19