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

如何在Swagger UI请求体示例值中隐藏字段但模型仍显示?

实现Swagger UI请求体示例隐藏字段但模型保留完整字段

这问题我之前也碰到过,核心思路就是把模型定义和示例内容分开处理:模型里保留所有字段确保完整性,而示例部分手动指定要展示的字段,就能实现示例精简但模型全量展示的效果。下面分不同版本的OpenAPI规范给你具体实现方案:

OpenAPI 3.x(主流版本)

在OpenAPI 3.x里,你可以在请求体的content下,单独定义example(单个示例)或者examples(多个示例),而模型的schema部分保持完整字段定义。

比如你要隐藏示例中的name字段,模型仍显示它,写法如下:

openapi: 3.0.3
info:
  title: 精简请求示例但保留完整模型
  version: 1.0.0
paths:
  /users:
    post:
      summary: 创建用户
      requestBody:
        required: true
        content:
          application/json:
            # 模型部分:定义所有字段,包括要隐藏的name
            schema:
              type: object
              properties:
                name:
                  type: string
                  description: 用户全名
                age:
                  type: integer
                  description: 用户年龄
                email:
                  type: string
                  format: email
                  description: 用户邮箱
              required: [name, email]  # 模型标记name为必填,不影响示例隐藏
            # 示例部分:只写需要展示的字段,跳过name
            example:
              age: 30
              email: "user@example.com"
      responses:
        '201':
          description: 用户创建成功

进阶:多示例切换

如果需要同时提供精简版和完整版示例,用examples字段即可:

content:
  application/json:
    schema: ... # 完整模型定义
    examples:
      精简示例:
        summary: 仅展示核心字段
        value:
          age: 30
          email: "user@example.com"
      完整示例:
        summary: 展示所有必填+可选字段
        value:
          name: "张三"
          age: 30
          email: "zhangsan@example.com"

Swagger 2.0(旧版本)

针对Swagger 2.0规范,做法类似,只是请求体的定义放在parameters的body参数里,同样单独指定example:

swagger: "2.0"
info:
  title: 精简请求示例但保留完整模型
  version: 1.0.0
paths:
  /users:
    post:
      summary: 创建用户
      parameters:
        - name: user
          in: body
          required: true
          # 模型部分:完整字段定义
          schema:
            type: object
            properties:
              name:
                type: string
                description: 用户全名
              age:
                type: integer
                description: 用户年龄
              email:
                type: string
                format: email
                description: 用户邮箱
            required: [name, email]
          # 示例部分:隐藏name字段
          example:
            age: 30
            email: "user@example.com"
      responses:
        '201':
          description: 用户创建成功

注意事项

  • 如果字段标记为required,模型里会显示必填标识,但示例里可以不写——不过要提醒接口使用者,实际请求时还是需要传入该必填字段,示例只是为了精简展示核心参数。
  • 这种方式完全符合OpenAPI/Swagger规范,不会破坏接口文档的完整性,只是调整了示例的展示内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 09:06:42