postman-collection-generator
Express、Next.js、Fastify、Hono などのAPIルート定義をスキャンし、エンドポイント・HTTPメソッド・パラメータを抽出してPostmanにインポート可能なコレクションJSONファイルを生成します。「Postmanコレクションを作成したい」「Postmanにエクスポートしたい」「Postmanファイルを生成して」といったリクエスト時に活用してください。
description の原文を見る
Generates Postman collection JSON files from Express, Next.js, Fastify, Hono, or other API routes. Scans route definitions, extracts endpoints, methods, params, and creates importable collections. Use when users request "generate postman collection", "export to postman", "create postman file", or "postman import".
SKILL.md 本文
Postman Collection Generator
APIコードベースからインポート可能なPostmanコレクションを自動生成します。
コアワークフロー
- ルートをスキャン: コードベース内のすべてのAPI ルート定義を探す
- メタデータを抽出: メソッド、パス、パラメータ、リクエストボディ、ヘッダー
- エンドポイントを整理: リソースまたはフォルダ構造でグループ化
- コレクションを生成: Postman Collection v2.1 JSON を作成
- 例を追加: リクエスト/レスポンス例を含める
- 変数を設定: ベースURL、認証トークン用の環境変数
サポートされているフレームワーク
| フレームワーク | ルートパターン | 検出方法 |
|---|---|---|
| Express | app.get(), router.post() | app/router 上のメソッドチェーン |
| Next.js | app/api/**/route.ts | ファイルベースのルーティング |
| Fastify | fastify.get(), ルートスキーマ | メソッド + スキーマデコレータ |
| Hono | app.get(), app.post() | Express に似た形式 |
| NestJS | @Get(), @Post() デコレータ | デコレータベース |
| Koa | router.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\": \"john@example.com\"\n}"
},
"url": {
"raw": "{{baseUrl}}/users",
"host": ["{{baseUrl}}"],
"path": ["users"]
}
}
}
]
}
],
"variable": [
{ "key": "baseUrl", "value": "http://localhost:3000/api" },
{ "key": "authToken", "value": "" }
]
}
ベストプラクティス
- 変数を使用:
{{baseUrl}}、{{authToken}}で柔軟性を実現 - エンドポイントをグループ化: リソース/機能フォルダで整理
- 説明を追加: 各エンドポイントの目的を文書化
- 例を含める: リクエストボディに現実的なデータを事前入力
- 認証を設定: コレクションレベルの認証を構成
- テストを追加: 基本的なレスポンス検証スクリプトを含める
- バージョン管理: コレクション JSON をリポジトリにコミット
- CI統合: ルート変更時に自動生成
出力チェックリスト
- コードベースからすべてのルートをスキャン
- エンドポイントをリソースでグループ化
- パスパラメータを抽出
- POST/PUT/PATCH のリクエストボディを含める
- 環境変数を設定
- 認証セットアップ(該当する場合)
- コレクションを v2.1 JSON としてエクスポート
- 環境テンプレートを作成
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- patricio0312rev
- ライセンス
- MIT
- 最終更新
- 不明
Source: https://github.com/patricio0312rev/skills / ライセンス: MIT
関連スキル
doubt-driven-development
重要な判断はすべて、本番環境への展開前に新しい視点から対抗的レビューを実施します。速度より正確性が重要な場合、不慣れなコードを扱う場合、本番環境・セキュリティに関わるロジック・取り消し不可の操作など影響度が高い場合、または後でバグを修正するよりも今検証する方が効率的な場合に活用してください。
apprun-skills
TypeScriptを使用したAppRunアプリケーションのMVU設計に関する総合的なガイダンスが得られます。コンポーネントパターン、イベントハンドリング、状態管理(非同期ジェネレータを含む)、パラメータと保護機能を備えたルーティング・ナビゲーション、vistestを使用したテストに対応しています。AppRunコンポーネントの設計・レビュー、ルートの配線、状態フローの管理、AppRunテストの作成時に活用してください。
desloppify
コードベースのヘルスチェックと技術負債の追跡ツールです。コード品質、技術負債、デッドコード、大規模ファイル、ゴッドクラス、重複関数、コードスメル、命名規則の問題、インポートサイクル、結合度の問題についてユーザーが質問した場合に使用してください。また、ヘルススコアの確認、次の改善項目の提案、クリーンアップ計画の作成をリクエストされた際にも対応します。29言語に対応しています。
debugging-and-error-recovery
テストが失敗したり、ビルドが壊れたり、動作が期待と異なったり、予期しないエラーが発生したりした場合に、体系的な根本原因デバッグをガイドします。推測ではなく、根本原因を見つけて修正するための体系的なアプローチが必要な場合に使用してください。
test-driven-development
テスト駆動開発により実装を進めます。ロジックの実装、バグの修正、動作の変更など、あらゆる場面で活用できます。コードが正常に動作することを証明する必要がある場合、バグ報告を受けた場合、既存機能を修正する予定がある場合に使用してください。
incremental-implementation
変更を段階的に実施します。複数のファイルに影響する機能や変更を実装する場合に使用してください。大量のコードを一度に書こうとしている場合や、タスクが一度では完結できないほど大きい場合に活用します。