A powerful CLI tool that converts Postman collections into complete API service files with TypeScript/JavaScript support and Axios/Fetch integration.
- One-command generation - Convert entire Postman collections instantly
- Clean naming conventions - Professional function and file names without numbers
- Enhanced type generation - Comprehensive TypeScript interfaces with namespaced types
- Organized output - Creates clean folder structure with one file per API group
- Authentication support - Automatically generates auth wrappers for secured APIs
- Multiple clients - Support for both Axios and Fetch API
- TypeScript ready - Full TypeScript support with proper type annotations
- Request parsing - Handles body, query params, headers, and auth parameters
- Prettier formatting - All generated code is automatically formatted
- Interactive mode - Choose options via CLI prompts or flags
npm install -g postman-to-apiOr use directly with npx:
npx postman-to-api ./collection.json --out ./src/api# Generate TypeScript API files with Axios
postman-to-api ./my-collection.json --out ./src/api --lang ts --client axios
# Generate JavaScript API files with Fetch
postman-to-api ./my-collection.json --out ./src/api --lang js --client fetch
# Interactive mode (prompts for options)
postman-to-api ./my-collection.json| Option | Description | Default | Values |
|---|---|---|---|
<collection> |
Path to Postman collection JSON file | Required | File path |
--out, -o |
Output directory for generated files | ./api (or ./src/api if src exists) |
Directory path |
--lang, -l |
Programming language | ts |
ts, js |
--client, -c |
HTTP client library | axios |
axios, fetch |
--types |
Generate TypeScript interfaces | false |
Boolean |
--no-interactive |
Skip prompts and use provided options | false |
Boolean |
If src folder exists:
src/
└── api/
├── auth.ts # Authentication functions
├── user-management.ts # User operations
├── product-management.ts # Product operations
├── order-management.ts # Order operations
├── category-management.ts # Category operations
├── payment-management.ts # Payment operations
├── validation-utilities.ts # Validation functions
├── baseUrl.ts # Base URL configuration
├── instance.ts # Axios instance with auth
├── routes.ts # Route definitions
├── types.ts # TypeScript interfaces (with --types)
└── index.ts # Main export file
If no src folder:
api/
├── auth.ts # Authentication functions
├── user-management.ts # User operations
├── product-management.ts # Product operations
├── order-management.ts # Order operations
├── category-management.ts # Category operations
├── payment-management.ts # Payment operations
├── validation-utilities.ts # Validation functions
├── baseUrl.ts # Base URL configuration
├── instance.ts # Axios instance with auth
├── routes.ts # Route definitions
├── types.ts # TypeScript interfaces (with --types)
└── index.ts # Main export file
import { apiInstance } from './instance';
import { buildRoute, GET_USERS_ROUTE, CREATE_USER_ROUTE } from './routes';
// Types
interface ApiResponse<T = any> {
data: T;
status: number;
statusText: string;
message?: string;
}
interface User {
id: string;
name: string;
email: string;
role: string;
}
interface CreateUserRequest {
name: string;
email: string;
password: string;
role?: string;
}
export async function getUsers(): Promise<ApiResponse<User[]>> {
try {
const route = buildRoute(GET_USERS_ROUTE);
const response = await apiInstance.get(route);
return {
data: response.data,
status: response.status,
statusText: response.statusText,
message: 'Users fetched successfully',
};
} catch (error) {
console.error('Error fetching users:', error);
const errorObj = error as any;
throw {
data: null,
status: errorObj.response?.status || 500,
statusText: errorObj.response?.statusText || 'Internal Server Error',
message: errorObj.message || 'Failed to fetch users',
};
}
}
export async function createUser(
userData: CreateUserRequest
): Promise<ApiResponse<User>> {
try {
const route = buildRoute(CREATE_USER_ROUTE);
const response = await apiInstance.post(route, { data: userData });
return {
data: response.data,
status: response.status,
statusText: response.statusText,
message: 'User created successfully',
};
} catch (error) {
console.error('Error creating user:', error);
const errorObj = error as any;
throw {
data: null,
status: errorObj.response?.status || 500,
statusText: errorObj.response?.statusText || 'Internal Server Error',
message: errorObj.message || 'Failed to create user',
};
}
}import { fetchWithAuth } from './instance';
import { buildRoute, GET_PRODUCTS_ROUTE, UPDATE_PRODUCT_ROUTE } from './routes';
export async function getProducts(category = null) {
try {
let route = buildRoute(GET_PRODUCTS_ROUTE);
if (category) {
route += `?category=${encodeURIComponent(category)}`;
}
const response = await fetchWithAuth(route, {
method: 'GET',
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return {
data,
status: response.status,
statusText: response.statusText,
message: 'Products fetched successfully',
};
} catch (error) {
console.error('Error fetching products:', error);
throw {
data: null,
status: error.status || 500,
statusText: error.statusText || 'Internal Server Error',
message: error.message || 'Failed to fetch products',
};
}
}
export async function updateProduct(productId, productData) {
try {
const route = buildRoute(UPDATE_PRODUCT_ROUTE, { productId });
const response = await fetchWithAuth(route, {
method: 'PATCH',
body: JSON.stringify(productData),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return {
data,
status: response.status,
statusText: response.statusText,
message: 'Product updated successfully',
};
} catch (error) {
console.error('Error updating product:', error);
throw {
data: null,
status: error.status || 500,
statusText: error.statusText || 'Internal Server Error',
message: error.message || 'Failed to update product',
};
}
}import axios, { AxiosInstance } from 'axios';
import { getBaseUrl } from './baseUrl';
// Create axios instance with default config
const apiInstance: AxiosInstance = axios.create({
baseURL: getBaseUrl(),
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
// Request interceptor
apiInstance.interceptors.request.use(
config => {
const token = getAuthToken();
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => Promise.reject(error)
);
// Response interceptor
apiInstance.interceptors.response.use(
response => response,
error => {
if (error.response?.status === 401) {
clearAuthToken();
}
return Promise.reject(error);
}
);
// Auth token management
function getAuthToken(): string | null {
return localStorage.getItem('authToken');
}
function setAuthToken(token: string): void {
localStorage.setItem('authToken', token);
}
function clearAuthToken(): void {
localStorage.removeItem('authToken');
}
export { apiInstance, setAuthToken, clearAuthToken, getAuthToken };export interface EcommerceAPI1CreateUserRequest {
name: string;
email: string;
password: string;
phone?: string;
address?: string;
}
export interface EcommerceAPI2LoginUserRequest {
email: string;
password: string;
remember_me?: boolean;
}
export interface EcommerceAPI3CreateProductRequest {
name: string;
description: string;
price: number;
category: string;
stock_quantity: number;
images?: File[];
}
export interface EcommerceAPI4UpdateProductRequest {
name?: string;
description?: string;
price?: number;
category?: string;
stock_quantity?: number;
is_active?: boolean;
}
export interface EcommerceAPI5CreateOrderRequest {
user_id: string;
items: Array<{
product_id: string;
quantity: number;
price: number;
}>;
shipping_address: {
street: string;
city: string;
state: string;
zip_code: string;
country: string;
};
payment_method: 'credit_card' | 'paypal' | 'stripe';
}Your Postman collection should be exported as a JSON file. The tool supports:
- ✅ Folders/Groups - Organized into separate API files with clean names
- ✅ Request methods - GET, POST, PUT, PATCH, DELETE
- ✅ Path parameters -
{{userId}}or{userId}format - ✅ Query parameters - Automatically detected and included
- ✅ Request bodies - JSON, form-data, urlencoded, GraphQL
- ✅ Authentication - Bearer tokens, API keys, Basic auth, OAuth2
- ✅ Headers - Custom headers with sanitized property names
- ✅ File uploads - Proper File type detection
- ✅ Environment variables - Base URLs and common values
- ✅ Clean naming - Removes numbers and special characters from function/file names
# Clone the repository
git clone <repo-url>
cd postman-to-api
# Install dependencies
npm install
# Build the project
npm run build
# Run in development
npm run dev ./examples/collection.json --out ./output
# Run tests
npm test
# Lint code
npm run lint
# Format code
npm run formatCheck out the examples/ directory for sample Postman collections and generated output.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
MIT License - see the LICENSE file for details.
# Generate e-commerce API with TypeScript and Axios (auto-detects src folder)
postman-to-api ecommerce-collection.json --lang ts --client axios --types
# Generate user management API with JavaScript and Fetch (custom output)
postman-to-api user-api.json --out ./services --lang js --client fetch
# Interactive mode - choose options via prompts
postman-to-api my-api-collection.json// If src folder exists, import from src/api
import {
getUsers,
createUser,
getProducts,
updateProduct,
createOrder,
getUserOrders,
} from './src/api';
// If no src folder, import from api
// import { ... } from './api';
// User management
const users = await getUsers();
console.log('All users:', users.data);
const newUser = await createUser({
name: 'John Doe',
email: 'john@example.com',
password: 'securePassword123',
role: 'customer',
});
// Product management
const products = await getProducts('electronics');
console.log('Electronics products:', products.data);
await updateProduct('product-123', {
name: 'Updated Product Name',
price: 299.99,
stock_quantity: 50,
});
// Order management
const order = await createOrder({
user_id: newUser.data.id,
items: [
{ product_id: 'product-123', quantity: 2, price: 299.99 },
{ product_id: 'product-456', quantity: 1, price: 149.99 },
],
shipping_address: {
street: '123 Main St',
city: 'New York',
state: 'NY',
zip_code: '10001',
country: 'USA',
},
payment_method: 'credit_card',
});
const userOrders = await getUserOrders(newUser.data.id);
console.log('User orders:', userOrders.data);- Clean naming conventions - Removed numbers from function and file names
- Enhanced type generation - Comprehensive TypeScript interfaces with namespaced types
- Improved request parsing - Better handling of body, query params, headers, and auth
- Professional file structure - Clean, organized output with descriptive names
- Better error handling - Comprehensive try-catch blocks with proper error responses
- Route management - Centralized route definitions with path parameter support
- Initial release
- TypeScript and JavaScript support
- Axios and Fetch API support
- Authentication wrapper generation
- Interactive CLI prompts
- Prettier code formatting