| name | postman-collection-generator |
| 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". |
Postman Collection Generator
Generate importable Postman collections from your API codebase automatically.
Core Workflow
- Scan routes: Find all API route definitions in the codebase
- Extract metadata: Methods, paths, params, request bodies, headers
- Organize endpoints: Group by resource or folder structure
- Generate collection: Create Postman Collection v2.1 JSON
- Add examples: Include request/response examples
- Configure variables: Environment variables for base URL, auth tokens
Supported Frameworks
| Framework | Route Pattern | Detection |
|---|
| Express | app.get(), router.post() | Method chaining on app/router |
| Next.js | app/api/**/route.ts | File-based routing |
| Fastify | fastify.get(), route schema | Method + schema decorators |
| Hono | app.get(), app.post() | Similar to Express |
| NestJS | @Get(), @Post() decorators | Decorator-based |
| Koa | router.get(), router.post() | Koa-router patterns |
Postman Collection v2.1 Schema
{
"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 Route Scanner
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[] = [];
code = fs.(filePath, );
ast = (code, {
: ,
: [],
});
(ast, {
(nodePath) {
callee = nodePath..;
(callee. === ) {
method = callee..;
httpMethods = [, , , , ];
(httpMethods.(method)) {
args = nodePath..;
(args[]?. === ) {
routePath = args[].;
routes.({
: method.(),
: routePath,
: (method, routePath),
: (routePath),
});
}
}
}
},
});
routes;
}
(): [] {
: [] = [];
pathParamRegex = ;
match;
((match = pathParamRegex.(routePath)) !== ) {
params.({
: match[],
: ,
: ,
});
}
params;
}
(): {
cleanPath = path.(, ).();
;
}
Next.js App Router Scanner
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, "/");
const methods = [, , , , , , ];
( method methods) {
(
content.() ||
content.() ||
content.()
) {
routes.({
method,
: (apiPath),
: file,
});
}
}
}
routes;
}
(): {
nextPath
.(, )
.(, );
}
Fastify Route Scanner
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");
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,
});
}
return routes;
}
Collection Generator
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: ;
}
(): {
: = {
: {
: options.,
: options. || ,
:
,
},
: [],
: [
{ : , : options., : },
{ : , : , : },
],
};
(options. === ) {
collection. = {
: ,
: [{ : , : , : }],
};
}
groupedRoutes = (routes);
( [resource, resourceRoutes] .(groupedRoutes)) {
: = {
: resource,
: resourceRoutes.( (route)),
};
collection..(folder);
}
collection;
}
(): {
pathSegments = route..().();
: = {
: route.,
: {
: route.,
: [
{ : , : , : },
],
: {
: ,
: [],
: pathSegments,
: route.
?.( p. === )
.( ({
: p.,
: p. || ,
: p.,
})),
},
: route.,
},
};
([, , ].(route.) && route.) {
item.. = {
: ,
: .(route., , ),
: { : { : } },
};
}
item;
}
(): <, []> {
: <, []> = {};
( route routes) {
parts = route..().();
resource = parts[] || parts[] || ;
(!groups[resource]) {
groups[resource] = [];
}
groups[resource].(route);
}
groups;
}
CLI Script
#!/usr/bin/env node
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[] = [];
(options.) {
:
routes = (options.);
;
:
routes = (path.(options., ));
;
:
routes = (options.);
;
:
.();
process.();
}
collection = (routes, {
: options.,
: options.,
: options.,
});
fs.(options., .(collection, , ));
.();
}
();
Environment Template
{
"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 }
]
}
Example Output
{
"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"
Best Practices
- Use variables:
{{baseUrl}}, {{authToken}} for flexibility
- Group endpoints: Organize by resource/feature folders
- Add descriptions: Document each endpoint's purpose
- Include examples: Pre-fill request bodies with realistic data
- Set up auth: Configure collection-level authentication
- Add tests: Include basic response validation scripts
- Version control: Commit collection JSON to repository
- CI integration: Auto-generate on route changes
Output Checklist