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

Swagger中如何基于枚举值动态变更GET接口的查询参数

实现Swagger基于枚举值动态展示查询参数的方案

前提说明

  • 该功能需要使用*OpenAPI 3.0+*版本规范支持,旧版Swagger 2.0无法实现参数的条件渲染逻辑,若你还在使用Swagger 2.0需要先完成规范版本升级,同时配套使用3.0+版本的Swagger UI
  • 若无法升级到OpenAPI 3.x,只能将所有可选参数都列在parameters中,在每个参数的描述里标注对应适用的document_type枚举值,无法实现自动隐藏效果

具体配置示例

你需要将关联的查询参数封装为对象结构,配合discriminator和oneOf实现动态判别,完整配置如下:

openapi: 3.0.3
paths:
  /your-api-path: # 替换成你的实际路由地址
    get:
      description: Validation Option
      tags:
        - Validation User and Supplier
      parameters:
        - in: query
          name: document_params
          style: form
          explode: true
          schema:
            type: object
            discriminator:
              propertyName: document_type
              mapping:
                GST: '#/components/schemas/GstDocumentParams'
                PAN: '#/components/schemas/PanDocumentParams'
            oneOf:
              - $ref: '#/components/schemas/GstDocumentParams'
              - $ref: '#/components/schemas/PanDocumentParams'
components:
  schemas:
    GstDocumentParams:
      type: object
      required:
        - document_type
        - gst_number
        - mobile
      properties:
        document_type:
          type: string
          minLength: 1
          maxLength: 20
          description: type of document used
          enum:
            - GST
        gst_number:
          type: string
          description: GST编号
        mobile:
          type: string
          description: 绑定手机号
    PanDocumentParams:
      type: object
      required:
        - document_type
        - pan_number
      properties:
        document_type:
          type: string
          minLength: 1
          maxLength: 20
          description: type of document used
          enum:
            - PAN
        pan_number:
          type: string
          description: PAN编号

配置说明

  • style: form和explode: true参数会让Swagger将对象内的所有属性平铺为独立的查询参数,最终发起请求的格式和你给出的示例完全一致,不会产生额外的参数嵌套
  • 以document_type作为判别字段,Swagger UI会自动根据你选择的枚举值切换展示对应的参数,必填校验规则也会同步更新
  • 如果你是用swagger-jsdoc这类注解工具生成Swagger配置,把上述schema结构转换成对应的JSDoc注解格式即可生效

效果验证

配置完成后打开Swagger UI进入对应接口页:

  • 选择document_type为GST时,界面会自动展示gst_number、mobile两个参数的输入框
  • 选择document_type为PAN时,界面会自动展示pan_number参数的输入框

内容的提问来源于stack exchange,提问作者King Of Gotham

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 09:48:04