api-mock-generator
v1.0.2
Published
Production-ready mock server generator from OpenAPI/Swagger specifications with 150+ dynamic templates
Readme
📖 Description
API Mock Server Generator - это мощный инструмент для автоматической генерации мок-серверов из OpenAPI 3.0/Swagger 2.0 спецификаций. Идеально подходит для разработки фронтенда без готового бэкенда, тестирования API и демонстрации проектов.
Ключевые особенности
- 🚀 Быстрый старт - запуск мок-сервера одной командой
- 🎭 150+ динамических шаблонов - генерация реалистичных данных
- 🎨 React UI панель - удобное управление эндпоинтами
- 📡 Real-time мониторинг - отслеживание запросов через WebSocket
- 🔒 Production-ready - защита от уязвимостей и DoS атак
- 🌍 Кроссплатформенность - Windows, Linux, macOS, Docker
- 📦 Экспорт коллекций - Postman и Insomnia
🔧 Технологии
Core Technologies
Backend Stack
- Node.js - JavaScript runtime environment
- TypeScript - Strongly typed programming language
- Express.js - Fast, minimalist web framework
- express-ws - WebSocket support for Express
- Commander.js - Complete CLI solution
- swagger-client - OpenAPI/Swagger parser
- js-yaml - YAML 1.2 parser and serializer
- @faker-js/faker - Generate massive amounts of fake data
- cors - CORS middleware
- body-parser - Request body parsing middleware
Frontend Stack
- React - JavaScript library for building user interfaces
- React Router - Declarative routing for React
- Vite - Next generation frontend tooling
Development Tools
📦 Installation
# Global installation
npm install -g api-mock-generator
# Or use with npx (no installation required)
npx api-mock-generator generate openapi.yamlRequirements:
- Node.js >= 16.x
- npm >= 7.x
🚀 Quick Start
# Generate mock server from OpenAPI specification
api-mock generate openapi.yaml --port=3000
# Open UI panel in browser
# http://localhost:3000/_uiExample OpenAPI Specification
Create api.yaml:
openapi: 3.0.0
info:
title: My API
version: 1.0.0
paths:
/users:
get:
responses:
'200':
description: List of users
content:
application/json:
schema:
type: array
items:
type: object
properties:
id:
type: string
format: uuid
name:
type: string
email:
type: string
format: emailRun:
api-mock generate api.yamlResult:
Mock server started on http://localhost:3000
GET http://localhost:3000/users
[
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "John Doe",
"email": "[email protected]"
}
]📚 Usage
CLI Options
api-mock generate <spec-file> [options]| Option | Alias | Description | Default |
|--------|-------|-------------|---------|
| --port | -p | Server port | 3000 |
| --host | -h | Server host | localhost |
| --ui-path | | UI panel path | /_ui |
Examples
# Start on custom port
api-mock generate api.yaml --port=8080
# Listen on all interfaces
api-mock generate api.yaml --host=0.0.0.0
# Custom UI path
api-mock generate api.yaml --ui-path=/_admin🎨 UI Panel
The web interface provides complete control over your mock server:
- 📊 Dashboard - Server statistics and quick actions
- 🔌 Endpoints - Manage endpoints and configure responses
- 📡 Monitor - Real-time request logging via WebSocket
- ⚙️ Settings - Server configuration
Access: http://localhost:3000/_ui
🎭 Dynamic Templates
Generate realistic data using 150+ built-in templates:
{
"id": "{{uuid}}",
"orderId": "{{order-id}}",
"user": {
"email": "{{email}}",
"name": "{{fullname}}",
"nickname": "{{nickname}}",
"role": "{{role}}",
"age": {{int:18:65}}
},
"order": {
"total": {{amount:10:1000:2:$}},
"status": "{{order-status}}",
"items": [
{
"product": "{{product-name}}",
"quantity": {{int:1:10}}
}
]
},
"payment": {
"method": "{{payment-status}}",
"transactionId": "{{transaction-id}}",
"cardNumber": "{{creditcard}}"
},
"timestamps": {
"createdAt": "{{date}}",
"updatedAt": "{{datetime}}"
}
}Template Categories
{{uuid}}- UUID v4{{fullname}},{{name}}- Full name{{firstname}}- First name{{lastname}}- Last name{{nickname}},{{nick}}- Username with number{{email}}- Email address{{phone}}- Phone number{{age:min:max}}- Age (default 18-65){{gender}}- Gender{{bio}}- Biography
{{role}}- User role (admin, user, moderator, etc.){{permission}}- Permission (read, write, delete, etc.)
{{order-id}},{{order_id}}- Order number (ORD-XXXXXXXX-XXXXXX){{invoice-id}}- Invoice number{{transaction-id}},{{txn-id}}- Transaction ID{{payment-id}}- Payment ID{{ticket-id}}- Ticket number{{booking-id}}- Booking ID{{subscription-id}}- Subscription ID{{session-id}}- Session ID
{{token}}- Token (32 chars){{api-key}}- API key (sk-XXXXXXXX){{secret-key}}- Secret key (64 chars){{access-token}}- Access token{{refresh-token}}- Refresh token
{{date}},{{datetime}}- ISO date/time{{date-past}}- Past date{{date-future}}- Future date{{timestamp}}- Current timestamp (ms){{timestamp-s}}- Current timestamp (seconds)
{{amount:min:max:decimals:symbol}}- Money amount{{price:min:max:decimals:symbol}}- Product price{{creditcard}}- Credit card number{{iban}}- IBAN{{currency-code}}- Currency code (USD, EUR){{bitcoin-address}}- Bitcoin address
{{product-name}}- Product name{{product-description}}- Product description{{category}}- Product category{{sku}}- Stock keeping unit{{barcode}}- Barcode
{{status}}- General status (active, inactive, pending){{order-status}}- Order status (pending, shipped, delivered){{payment-status}}- Payment status (paid, failed, refunded){{user-status}}- User status (active, suspended, banned)
🐳 Docker
Using Docker Compose
docker-compose up -dBuild Custom Image
docker build -t api-mock-generator .
docker run -d \
-p 3000:3000 \
-v $(pwd)/openapi.yaml:/app/openapi.yaml \
api-mock-generator \
generate /app/openapi.yaml --host=0.0.0.0🛠️ Development
Project Structure (Monorepo)
api-mock-generator/
├── packages/
│ ├── shared/ # Common types and utilities
│ ├── core/ # OpenAPI parser and data generator
│ ├── server/ # Express server
│ ├── ui/ # React UI panel
│ └── cli/ # CLI tool
├── example-api.yaml # Example OpenAPI specification
└── README.mdSetup
# Install dependencies
npm install
# Build all packages
npm run build
# Run in development mode
npm run dev
# Run linter
npm run lint
# Test with example
node packages/cli/dist/cli.js generate example-api.yaml🔒 Security
Built-in protection against:
- ✅ Path Traversal - File path validation
- ✅ YAML Injection - Safe YAML parsing
- ✅ DoS Attacks - Request size limits
- ✅ XSS - Input sanitization
- ✅ CORS - Configurable CORS rules
🌍 Platform Support
- ✅ Windows 10/11
- ✅ Linux (Ubuntu, Debian, CentOS, Fedora, etc.)
- ✅ macOS (Intel & Apple Silicon)
- ✅ Docker (any platform)
📝 Use Cases
1. Frontend Development Without Backend
# Create OpenAPI spec
# Start mock server
api-mock generate api.yaml
# Frontend connects to http://localhost:30002. API Documentation & Demos
# Run on public host
api-mock generate api.yaml --host=0.0.0.0 --port=80
# Share Postman collection with clients
# Available at http://your-server/_ui3. Testing Race Conditions
Enable request queue in UI panel to test concurrent requests handling.
4. Contract Testing
Validate your API contracts before backend implementation.
🔗 Resources
🤝 Support
If you find this project useful, please consider giving it a ⭐️ on GitHub!
👨💻 Author
Дмитрий (Utkautka1) - Full-stack разработчик
- 🌐 Портфолио: dmitry-fullstack.vercel.app
- 💻 GitHub: @Utkautka1
- 📦 NPM: api-mock-generator
📄 License
This project is MIT licensed.
