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

如何在Swagger中按所选服务器过滤路由并按标签分组

实现OpenAPI文档服务器切换时的路由过滤

第一步:给路由绑定对应服务器

先在你的OpenAPI 3.1.0规范里,给每个路径明确指定所属服务器。OpenAPI允许单个路径配置servers字段,把路由和对应服务器URL关联起来,示例如下:

paths:
  # 属于主TCP服务的路由
  /patterns/list:
    servers:
      - url: http://localhost:8000
    get:
      tags:
        - patterns
      summary: 获取patterns列表
      # 其他接口配置...

  # 属于WebSocket服务的路由
  /widgets/ws/connect:
    servers:
      - url: ws://localhost:8080
    get:
      tags:
        - widgets
      summary: 连接WebSocket
      # 其他接口配置...

如果某个路由未配置servers,可以默认将其归到主服务器,后续JS逻辑可针对性处理这种情况。

第二步:用Swagger UI自定义JS实现过滤逻辑

假设你使用Swagger UI渲染文档,可在现有JS代码基础上,添加服务器切换监听和路由过滤逻辑:

// 保存Swagger UI实例引用(实例化时务必保留)
const swaggerUi = SwaggerUIBundle({
  url: "/your-openapi-spec.yaml",
  dom_id: '#swagger-ui',
  // 你的其他配置项...
});

// 监听服务器切换事件
swaggerUi.on('serverChange', function(selectedServer) {
  const targetServerUrl = selectedServer.url;

  // 遍历所有标签分组
  document.querySelectorAll('.tag-wrapper').forEach(tagGroup => {
    let hasVisibleRoutes = false;

    // 遍历当前标签下的每个路由项
    tagGroup.querySelectorAll('.operation').forEach(routeItem => {
      // 获取路由的路径标识(格式如"paths-/patterns/list")
      const pathKey = routeItem.getAttribute('data-path').replace('paths-', '');
      // 从OpenAPI spec中获取该路径的定义
      const routeDef = swaggerUi.spec.paths[pathKey];

      // 判断当前路由是否匹配选中的服务器
      let isMatch = false;
      if (routeDef.servers) {
        // 检查路由绑定的服务器列表是否包含选中的URL
        isMatch = routeDef.servers.some(server => server.url === targetServerUrl);
      } else {
        // 未配置servers的路由,默认归到主服务器(可按需调整规则)
        isMatch = targetServerUrl === 'http://localhost:8000';
      }

      // 控制路由项的显示/隐藏
      routeItem.style.display = isMatch ? 'block' : 'none';
      if (isMatch) hasVisibleRoutes = true;
    });

    // 若当前标签下无可见路由,则隐藏整个标签分组
    tagGroup.style.display = hasVisibleRoutes ? 'block' : 'none';
  });
});

// 页面初始化时触发一次,确保默认选中服务器的路由正确显示
const initialSelectedServer = swaggerUi.getState().selectedServer;
if (initialSelectedServer) {
  swaggerUi.trigger('serverChange', initialSelectedServer);
}

关键细节说明

  • .tag-wrapper和.operation是Swagger UI默认的DOM类名,若你自定义了UI样式,需对应调整选择器;
  • 你之前写的隐藏Try It Out按钮的逻辑无需改动——过滤逻辑直接隐藏整个路由项,按钮自然会被隐藏;
  • 若路由同时属于多个服务器,只需在servers数组中添加对应URL,代码会自动识别匹配;
  • 若需调整隐藏/显示的样式表现(比如用visibility替代display),可修改style.display的取值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 13:31:15