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

如何在OpenAPI 2.0(Swagger 2.0)中设置多类型请求体参数

在OpenAPI 2.0中实现混合对象与原始类型的请求体

问题原因

OpenAPI 2.0规范不允许一个接口定义多个in: body的参数,你当前的写法把criteria、offset、limit分别作为独立的body参数,违反了规范,因此Swagger Editor报错。

解决方案:封装顶层请求体对象

需要创建一个包含所有请求体字段的顶层对象定义,将criteria(复用现有Criteria定义)、offset、limit作为该对象的属性,然后接口仅声明一个body参数引用这个顶层对象。

修改后的完整OpenAPI定义示例

paths:
  "/user":
    post:
      tags:
        - "user Service"
      summary: "Returns a list of user"
      operationId: "searchUsers"
      produces:
        - "application/json"
      parameters:
        - in: "body"
          name: "requestBody"
          required: true
          schema:
            $ref: "#/definitions/UserSearchRequest"
      responses:
        "200":
          description: "Success"
          schema:
            $ref: "#/definitions/user"

definitions:
  Criteria:
    type: "object"
    required:
      - "key"
    properties:
      key:
        type: "string"
        description: "search key."
        pattern: "[A-Za-z0-9-]+"
        minLength: 1
        maxLength: 30
      code:
        type: "string"
        description: "emp code filter on."
        pattern: "^[A-Za-z0-9]+"
        minLength: 0
        maxLength: 9
  UserSearchRequest:
    type: "object"
    required:
      - "criteria"
    properties:
      criteria:
        $ref: "#/definitions/Criteria"
      offset:
        type: "integer"
        description: "The offset for pagination."
        format: "int32"
        default: 0
        minimum: 0
        required: false
      limit:
        type: "integer"
        description: "The maximum number user"
        format: "int32"
        minimum: 1
        maximum: 30
        default: 30
        required: false

说明

  • 新增的UserSearchRequest对象完全匹配你期望的JSON请求体结构。
  • 接口仅保留一个in: body参数,符合OpenAPI 2.0规范要求。
  • 原有的Criteria定义无需修改,可直接复用。

内容的提问来源于stack exchange,提问作者jcrshankar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 02:06:35