mcpField
P
postman-collection-generator

postman-collection-generator

github.com/patricio0312rev测试与质量63687 次安装41 周前更新
代码仓库

关于 postman-collection-generator

面向 API 开发者的代码库扫描技能,可从路由定义提取端点信息并生成可导入的 Postman Collection v2.1。支持多种常见框架,并可组织端点、添加示例和环境变量。

主要功能

  1. 01扫描 API 路由定义
  2. 02提取方法、路径与请求元数据
  3. 03按资源或目录组织端点
  4. 04生成 Postman Collection v2.1 JSON
  5. 05添加请求示例和环境变量模板

适用场景

  1. 01为现有代码库生成 Postman 集合
  2. 02整理多个资源的 API 端点
  3. 03为本地开发配置基础 URL 与认证变量
  4. 04在路由变更后重新生成集合

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/patricio0312rev/skills --skill postman-collection-generator

安装后在 Claude Code 中输入/postman-collection-generator确认已加载。

详细介绍

Postman 集合生成器

根据 API 代码库自动生成可导入的 Postman 集合。

核心工作流

  1. 扫描路由:查找代码库中的所有 API 路由定义
  2. 提取元数据:方法、路径、参数、请求正文、请求头
  3. 整理端点:按资源或文件夹结构分组
  4. 生成集合:创建 Postman Collection v2.1 JSON
  5. 添加示例:包含请求/响应示例
  6. 配置变量:用于基本 URL、身份验证令牌的环境变量

支持的框架

框架路由模式检测方式
Expressapp.get(), router.post()app/router 上的方法链式调用
Next.jsapp/api/**/route.ts基于文件的路由
Fastifyfastify.get(), route schema方法和 schema 装饰器
Honoapp.get(), app.post()类似 Express
NestJS@Get(), @Post() decorators基于装饰器
Koarouter.get(), router.post()Koa-router 模式

Postman Collection v2.1 架构

{
  "info": {
    "name": "API Collection",
    "description": "Auto-generated from codebase",
    "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
  },
  "item": [],
  "variable": [],
  "auth": {}
}

Express 路由扫描器

// scripts/generate-postman.ts
import * as fs from "fs";
import * as path from "path";
import { parse } from "@babel/parser";
import traverse from "@babel/traverse";

interface RouteInfo {
  method: string;
  path: string;
  name: string;
  description?: string;
  params?: ParamInfo[];
  body?: Record<string, unknown>;
  headers?: Record<string, string>;
}

interface ParamInfo {
  name: string;
  type: "path" | "query";
  description?: string;
  example?: string;
}

function scanExpressRoutes(filePath: string): RouteInfo[] {
  const routes: RouteInfo[] = [];
  const code = fs.readFileSync(filePath, "utf-8");

  const ast = parse(code, {
    sourceType: "module",
    plugins: ["typescript"],
  });

  traverse(ast, {
    CallExpression(nodePath) {
      const callee = nodePath.node.callee;

      if (callee.type === "MemberExpression") {
        const method = callee.property.name;
        const httpMethods = ["get", "post", "put", "patch", "delete"];

        if (httpMethods.includes(method)) {
          const args = nodePath.node.arguments;
          if (args[0]?.type === "StringLiteral") {
            const routePath = args[0].value;

            routes.push({
              method: method.toUpperCase(),
              path: routePath,
              name: generateRouteName(method, routePath),
              params: extractParams(routePath),
            });
          }
        }
      }
    },
  });

  return routes;
}

function extractParams(routePath: string): ParamInfo[] {
  const params: ParamInfo[] = [];
  const pathParamRegex = /:(\w+)/g;
  let match;

  while ((match = pathParamRegex.exec(routePath)) !== null) {
    params.push({
      name: match[1],
      type: "path",
      example: `{{${match[1]}}}`,
    });
  }

  return params;
}

function generateRouteName(method: string, path: string): string {
  const cleanPath = path.replace(/[/:]/g, " ").trim();
  return `${method.toUpperCase()} ${cleanPath}`;
}

Next.js App Router 扫描器

// scripts/scan-nextjs-routes.ts
import * as fs from "fs";
import * as path from "path";
import { glob } from "glob";

interface NextApiRoute {
  method: string;
  path: string;
  filePath: string;
}

async function scanNextJsRoutes(appDir: string): Promise<NextApiRoute[]> {
  const routes: NextApiRoute[] = [];
  const routeFiles = await glob(`${appDir}/**/route.{ts,js}`);

  for (const file of routeFiles) {
    const content = fs.readFileSync(file, "utf-8");
    const relativePath = path.relative(appDir, path.dirname(file));
    const apiPath = "/" + relativePath.replace(/\\/g, "/");

    // Detect exported HTTP methods
    const methods = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];

    for (const method of methods) {
      if (
        content.includes(`export async function ${method}`) ||
        content.includes(`export function ${method}`) ||
        content.includes(`export const ${method}`)
      ) {
        routes.push({
          method,
          path: convertNextPathToPostman(apiPath),
          filePath: file,
        });
      }
    }
  }

  return routes;
}

function convertNextPathToPostman(nextPath: string): string {
  // Convert [param] to :param
  return nextPath
    .replace(/\[\.\.\.(\w+)\]/g, ":$1*") // [...slug] -> :slug*
    .replace(/\[(\w+)\]/g, ":$1"); // [id] -> :id
}

Fastify 路由扫描器

// scripts/scan-fastify-routes.ts
interface FastifyRoute {
  method: string;
  path: string;
  schema?: {
    body?: object;
    querystring?: object;
    params?: object;
    response?: object;
  };
}

function scanFastifyRoutes(filePath: string): FastifyRoute[] {
  const routes: FastifyRoute[] = [];
  const code = fs.readFileSync(filePath, "utf-8");

  // Match fastify.get('/path', { schema: ... }, handler)
  const routeRegex =
    /fastify\.(get|post|put|patch|delete)\s*\(\s*['"`]([^'"`]+)['"`]\s*,\s*(\{[\s\S]*?\})\s*,/g;

  let match;
  while ((match = routeRegex.exec(code)) !== null) {
    const [, method, path, optionsStr] = match;

    routes.push({
      method: method.toUpperCase(),
      path,
      // Parse schema from options if available
    });
  }

  return routes;
}

集合生成器

// scripts/generate-collection.ts
interface PostmanCollection {
  info: {
    name: string;
    description: string;
    schema: string;
  };
  item: PostmanItem[];
  variable: PostmanVariable[];
  auth?: PostmanAuth;
}

interface PostmanItem {
  name: string;
  request: {
    method: string;
    header: PostmanHeader[];
    url: PostmanUrl;
    body?: PostmanBody;
    description?: string;
  };
  response?: PostmanResponse[];
}

interface PostmanUrl {
  raw: string;
  host: string[];
  path: string[];
  query?: PostmanQuery[];
  variable?: PostmanPathVariable[];
}

interface PostmanVariable {
  key: string;
  value: string;
  type: string;
}

function generatePostmanCollection(
  routes: RouteInfo[],
  options: {
    name: string;
    baseUrl: string;
    description?: string;
    auth?: "bearer" | "basic" | "apikey";
  }
): PostmanCollection {
  const collection: PostmanCollection = {
    info: {
      name: options.name,
      description: options.description || "Auto-generated API collection",
      schema:
        "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
    },
    item: [],
    variable: [
      { key: "baseUrl", value: options.baseUrl, type: "string" },
      { key: "authToken", value: "", type: "string" },
    ],
  };

  // Add auth configuration
  if (options.auth === "bearer") {
    collection.auth = {
      type: "bearer",
      bearer: [{ key: "token", value: "{{authToken}}", type: "string" }],
    };
  }

  // Group routes by resource
  const groupedRoutes = groupRoutesByResource(routes);

  for (const [resource, resourceRoutes] of Object.entries(groupedRoutes)) {
    const folder: PostmanItem = {
      name: resource,
      item: resourceRoutes.map((route) => createPostmanRequest(route)),
    };
    collection.item.push(folder);
  }

  return collection;
}

function createPostmanRequest(route: RouteInfo): PostmanItem {
  const pathSegments = route.path.split("/").filter(Boolean);

  const item: PostmanItem = {
    name: route.name,
    request: {
      method: route.method,
      header: [
        { key: "Content-Type", value: "application/json", type: "text" },
      ],
      url: {
        raw: `{{baseUrl}}${route.path}`,
        host: ["{{baseUrl}}"],
        path: pathSegments,
        variable: route.params
          ?.filter((p) => p.type === "path")
          .map((p) => ({
            key: p.name,
            value: p.example || "",
            description: p.description,
          })),
      },
      description: route.description,
    },
  };

  // Add request body for POST/PUT/PATCH
  if (["POST", "PUT", "PATCH"].includes(route.method) && route.body) {
    item.request.body = {
      mode: "raw",
      raw: JSON.stringify(route.body, null, 2),
      options: { raw: { language: "json" } },
    };
  }

  return item;
}

function groupRoutesByResource(
  routes: RouteInfo[]
): Record<string, RouteInfo[]> {
  const groups: Record<string, RouteInfo[]> = {};

  for (const route of routes) {
    // Extract resource from path (e.g., /api/users/:id -> users)
    const parts = route.path.split("/").filter(Boolean);
    const resource = parts[1] || parts[0] || "root";

    if (!groups[resource]) {
      groups[resource] = [];
    }
    groups[resource].push(route);
  }

  return groups;
}

CLI 脚本

#!/usr/bin/env node
// scripts/postman-gen.ts
import * as fs from "fs";
import * as path from "path";
import { program } from "commander";

program
  .name("postman-gen")
  .description("Generate Postman collection from API routes")
  .option("-f, --framework <type>", "Framework type", "express")
  .option("-s, --source <path>", "Source directory", "./src")
  .option("-o, --output <path>", "Output file", "./postman-collection.json")
  .option("-n, --name <name>", "Collection name", "API Collection")
  .option("-b, --base-url <url>", "Base URL", "http://localhost:3000")
  .option("-a, --auth <type>", "Auth type (bearer|basic|apikey)")
  .parse();

const options = program.opts();

async function main() {
  let routes: RouteInfo[] = [];

  switch (options.framework) {
    case "express":
      routes = await scanExpressProject(options.source);
      break;
    case "nextjs":
      routes = await scanNextJsRoutes(path.join(options.source, "app/api"));
      break;
    case "fastify":
      routes = await scanFastifyProject(options.source);
      break;
    default:
      console.error(`Unsupported framework: ${options.framework}`);
      process.exit(1);
  }

  const collection = generatePostmanCollection(routes, {
    name: options.name,
    baseUrl: options.baseUrl,
    auth: options.auth,
  });

  fs.writeFileSync(options.output, JSON.stringify(collection, null, 2));
  console.log(`Generated ${options.output} with ${routes.length} endpoints`);
}

main();

环境模板

{
  "name": "Development",
  "values": [
    { "key": "baseUrl", "value": "http://localhost:3000/api", "enabled": true },
    { "key": "authToken", "value": "", "enabled": true, "type": "secret" },
    { "key": "userId", "value": "1", "enabled": true }
  ]
}

输出示例

{
  "info": {
    "name": "My API",
    "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
  },
  "item": [
    {
      "name": "Users",
      "item": [
        {
          "name": "GET users",
          "request": {
            "method": "GET",
            "url": {
              "raw": "{{baseUrl}}/users",
              "host": ["{{baseUrl}}"],
              "path": ["users"],
              "query": [
                { "key": "page", "value": "1" },
                { "key": "limit", "value": "10" }
              ]
            }
          }
        },
        {
          "name": "GET user by ID",
          "request": {
            "method": "GET",
            "url": {
              "raw": "{{baseUrl}}/users/:id",
              "host": ["{{baseUrl}}"],
              "path": ["users", ":id"],
              "variable": [{ "key": "id", "value": "{{userId}}" }]
            }
          }
        },
        {
          "name": "POST create user",
          "request": {
            "method": "POST",
            "header": [{ "key": "Content-Type", "value": "application/json" }],
            "body": {
              "mode": "raw",
              "raw": "{\n  \"name\": \"John Doe\",\n  \"email\": \"[email protected]\"\n}"
            },
            "url": {
              "raw": "{{baseUrl}}/users",
              "host": ["{{baseUrl}}"],
              "path": ["users"]
            }
          }
        }
      ]
    }
  ],
  "variable": [
    { "key": "baseUrl", "value": "http://localhost:3000/api" },
    { "key": "authToken", "value": "" }
  ]
}

最佳实践

  1. 使用变量:用 {{baseUrl}}、{{authToken}} 提高灵活性
  2. 对端点分组:按资源/功能文件夹整理
  3. 添加描述:说明每个端点的用途
  4. 包含示例:用贴近实际的数据预填请求正文
  5. 设置身份验证:配置集合级身份验证
  6. 添加测试:加入基本的响应验证脚本
  7. 版本控制:将集合 JSON 提交到代码库
  8. CI 集成:在路由变更时自动生成

输出检查清单

  • 已扫描代码库中的所有路由
  • 已按资源对端点分组
  • 已提取路径参数
  • 已为 POST/PUT/PATCH 包含请求正文
  • 已配置环境变量
  • 已设置身份验证(如适用)
  • 已将集合导出为 v2.1 JSON
  • 已创建环境模板

评论

支持 Markdown