Skip to content

CLI tool to generate TypeScript/JavaScript API service files from Postman collections. Supports Axios and Fetch with authentication, route management, and modern project structure.

License

Notifications You must be signed in to change notification settings

Anshkaran7/postman-to-api

Repository files navigation

Postman to API Generator

A powerful CLI tool that converts Postman collections into complete API service files with TypeScript/JavaScript support and Axios/Fetch integration.

Features

  • 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

Installation

npm install -g postman-to-api

Or use directly with npx:

npx postman-to-api ./collection.json --out ./src/api

Quick Start

Basic Usage

# 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

CLI Options

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

Generated Structure

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

Example Output

TypeScript + Axios

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',
    };
  }
}

JavaScript + Fetch

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',
    };
  }
}

Instance File (Axios)

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 };

TypeScript Interfaces (with --types)

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';
}

Postman Collection Requirements

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

Development

# 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 format

Examples

Check out the examples/ directory for sample Postman collections and generated output.

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

MIT License - see the LICENSE file for details.

Usage Examples

Basic Generation

# 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

Import and Use

// 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);

Changelog

v1.0.2

  • 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

v1.0.0

  • Initial release
  • TypeScript and JavaScript support
  • Axios and Fetch API support
  • Authentication wrapper generation
  • Interactive CLI prompts
  • Prettier code formatting

About

CLI tool to generate TypeScript/JavaScript API service files from Postman collections. Supports Axios and Fetch with authentication, route management, and modern project structure.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published