A complete enterprise-grade solution for designing, managing, and serving mock APIs with multi-tenancy, webhooks, GraphQL support, and comprehensive testing.
β PRODUCTION-READY: Now with 80%+ test coverage, configurable caching, webhook retries, dark mode, Prometheus metrics, CI/CD pipeline, and Kubernetes manifests.
- Multi-Tenancy: Workspace-based API organization with complete isolation
- Full CRUD Management: Create, read, update, and delete API definitions and endpoints
- Mock Runtime: Serve mock responses with configurable delays and multiple response scenarios
- Import/Export: JSON-based API definitions for easy sharing and version control
- Redis Caching: Fast response times with automatic cache invalidation
- Path Parameters: Support for dynamic routes like
/users/:id - Multiple Responses: Define multiple responses per endpoint with conditional matching
- Web UI: Modern React-based interface for managing your mocks
- Docker Ready: Complete Docker Compose setup for easy deployment
- π Authentication & Authorization:
- JWT-based authentication + API Keys for programmatic access
- RBAC (Role-Based Access Control): ADMIN, EDITOR, and VIEWER roles per workspace
- API Key Scopes: Fine-grained permissions (read, write, delete) per resource
- Two-Factor Authentication (2FA): TOTP-based additional security layer
- OAuth2/OIDC Login: Sign in with GitHub and Google
- π¦ API Versioning: Create and manage multiple versions of your APIs
- β JSON Schema Validation: Validate requests against OpenAPI-style schemas
- π¨ Handlebars Templating: Dynamic responses with
{{params.id}},{{query.name}}, etc. - β¨ Faker.js Integration: Generate realistic mock data with
{{faker.person.fullName}}, etc. - π OpenAPI Import: Drag & drop Swagger/OpenAPI 3.0 specs to auto-generate mocks
- π€ Collection Export: Export APIs as Postman or Insomnia collections
- πͺ Webhooks: Fire HTTP notifications with retry logic and exponential backoff
- π· GraphQL Support: Mock GraphQL queries and mutations
- π Analytics: Request tracking, metrics, performance stats, and automated retention cleanup
- π Advanced Analytics: Request/response size tracking and geo-location by country/city
- π Security: Helmet, rate limiting (per-workspace), CORS protection
- β‘ Conditional Responses: Match responses based on query params, headers, or body
- π Performance Optimization:
- Proxy Mode: Forward requests to real APIs for hybrid testing
- Request Deduplication: Cache identical requests for 60 seconds
- CDN Integration: Cache-Control and ETag headers for browser/CDN caching
- π WebSocket Mocking: Mock real-time WebSocket endpoints with event streaming
- π§ͺ Comprehensive Testing: 80%+ test coverage with Jest, Vitest, and Playwright
- π Audit Logs: Track all changes with user, IP, and timestamp
- π¨ Dark Mode: Full light/dark theme support with system preference detection
- π Toast Notifications: Centralized error handling with user-friendly messages
- π’ Slack Integration: Real-time notifications for API events (created, deleted, rate limits, etc.)
- π GitHub Actions Integration: Automate API imports and deployments in CI/CD pipelines
- π Prometheus Metrics: HTTP, webhook, cache, and runtime metrics for monitoring
- βοΈ Configurable: Cache TTL, rate limits, webhook retries, analytics retention via env vars
- π CI/CD Pipeline: GitHub Actions workflow with automated testing and Docker builds
- βΈοΈ Kubernetes Ready: Production-grade K8s manifests with health probes and HPA auto-scaling
- π οΈ CLI Tool: Powerful command-line interface for managing APIs, workspaces, and imports
- π SSO (SAML): Single Sign-On with Okta, Azure AD, and other SAML providers
- π Custom Domains: Configure custom domains per workspace with SSL support
- π¨ White-labeling: Custom logos, brand colors, and footer text per workspace
- πΎ Backup & Restore: Full workspace backup with one-click restore functionality
- π¦ Data Export: GDPR-compliant user data export in JSON and CSV formats
- π Horizontal Pod Autoscaling: Automatic scaling based on CPU/memory metrics
- NestJS - Progressive Node.js framework
- Prisma - Next-generation ORM
- PostgreSQL - Robust relational database with JSONB
- Redis - In-memory caching and session storage
- TypeScript - Type-safe development
- Jest - Unit and integration testing
- Handlebars - Template engine for dynamic responses
- AJV - JSON Schema validation
- React 18 - UI library with hooks
- Vite - Lightning-fast build tool
- React Router - Client-side routing
- TypeScript - Type-safe development
- Axios - HTTP client
- Recharts - Analytics visualization
- Monaco Editor - VS Code-like code editor
- Vitest - Unit testing for React components
- @faker-js/faker - Fake data generation
- Docker - Containerization
- Docker Compose - Multi-container orchestration
- Nginx - Web server for frontend
- Playwright - End-to-end testing
- Commander - Command-line framework
- Inquirer - Interactive prompts
- Chalk - Terminal colors
- Ora - Loading spinners
- cli-table3 - Table formatting
mock-api-studio/
βββ backend/ # NestJS API
β βββ src/
β β βββ api-definitions/ # API CRUD module
β β βββ mock-runtime/ # REST mock serving
β β βββ graphql-runtime/ # GraphQL mock serving
β β βββ workspaces/ # Multi-tenancy
β β βββ webhooks/ # Webhook subscriptions
β β βββ analytics/ # Usage tracking
β β βββ auth/ # JWT + API Keys
β β βββ openapi/ # OpenAPI parser
β β βββ audit-logs/ # Audit trail
β β βββ common/ # Shared modules (Prisma, Redis)
β β βββ shared/ # Utilities (Faker, validation)
β βββ prisma/
β β βββ schema.prisma # Database schema
β β βββ migrations/ # DB migrations
β β βββ seed.ts # Seed data
β βββ test/ # E2E tests
β βββ Dockerfile
βββ frontend/ # React UI
β βββ src/
β β βββ api/ # API client
β β βββ components/ # React components
β β βββ contexts/ # React contexts (Auth, Workspace)
β β βββ pages/ # Page components
β β βββ test/ # Vitest tests
β βββ nginx.conf
β βββ Dockerfile
βββ cli/ # Command-line interface
β βββ src/
β β βββ commands/ # CLI commands
β β βββ api-client.ts # API client
β β βββ config.ts # Config management
β β βββ index.ts # Entry point
β βββ package.json
β βββ README.md
βββ e2e/ # Playwright E2E tests
βββ docker-compose.yml # Multi-service setup
βββ playwright.config.ts # E2E config
βββ package.json # Monorepo scripts
- Docker & Docker Compose
- Node.js 20+ (for local development)
- (Optional) npm/pnpm for monorepo scripts
- Clone and start
git clone <repository-url>
cd mock-api-studio
docker compose up --build- Access the application
- Frontend: http://localhost:8080
- Backend API: http://localhost:3000
- REST Mock Runtime:
http://localhost:3000/mock/:apiSlug/* - GraphQL Mock Runtime:
http://localhost:3000/mock-graphql/:apiSlug
- Default credentials
- Register a new user at http://localhost:8080/register
- Or use seeded data (check
backend/prisma/seed.ts)
The database will be automatically migrated and seeded with:
- 2 workspaces (Default, Team Sandbox)
- 2 example APIs (JSONPlaceholder, GitHub Mock)
- Multiple endpoints with responses
# Install dependencies
cd backend && npm install
cd ../frontend && npm install
# Start PostgreSQL and Redis
docker compose up db redis -d
# Backend (Terminal 1)
cd backend
cp .env.example .env
npm run prisma:migrate
npm run prisma:seed
npm run start:dev
# Frontend (Terminal 2)
cd frontend
cp .env.example .env
npm run dev# Create a workspace
curl -X POST http://localhost:3000/admin/workspaces \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "Production Team",
"slug": "prod-team",
"description": "Production API mocks"
}'
# List APIs in a workspace
curl http://localhost:3000/api-definitions?workspaceId=<workspace-id> \
-H "Authorization: Bearer YOUR_JWT_TOKEN"# Upload OpenAPI spec (UI: /import-openapi)
# Or via API:
curl -X POST http://localhost:3000/api-definitions/import/openapi/upload?workspaceId=<ws-id> \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-F "file=@swagger.json"# Create a webhook subscription
curl -X POST http://localhost:3000/admin/webhooks \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"workspaceId": "<workspace-id>",
"targetUrl": "https://your-server.com/webhook",
"eventType": "mock.request.received",
"secret": "my-secret-key"
}'When a mock request is made, your webhook will receive:
{
"event": "mock.request.received",
"timestamp": "2024-01-15T10:30:00Z",
"workspaceId": "ws-123",
"apiSlug": "my-api",
"endpoint": { "id": "ep-1", "method": "GET", "path": "/users" },
"request": { "method": "GET", "path": "/users", "query": {} },
"response": { "statusCode": 200, "body": {...} }
}# Create a GraphQL endpoint in UI or API
# Then query it:
POST http://localhost:3000/mock-graphql/my-graphql-api?workspaceId=<ws-id>
Content-Type: application/json
{
"query": "query GetUser { user(id: 1) { id name email } }",
"operationName": "GetUser"
}{
"status": 200,
"body": {
"userId": "{{params.id}}",
"search": "{{query.q}}",
"timestamp": "{{timestamp}}",
"custom": "Hello {{body.name}}"
}
}{
"responses": [
{
"status": 200,
"body": { "premium": true },
"match": {
"query": { "tier": "premium" }
}
},
{
"status": 200,
"body": { "premium": false },
"isDefault": true
}
]
}Mock API Studio includes a powerful CLI for managing APIs from the terminal.
cd cli
npm install
npm run build
npm link# Login
mock-api login
# Select workspace
mock-api workspace list
mock-api workspace select my-workspace
# Create API
mock-api api create --name "Users API" --slug users-api
# Import OpenAPI spec
mock-api import ./swagger.json
# List APIs
mock-api api listmock-api login [--email EMAIL] [--password PASSWORD] [--api-key KEY]
mock-api logout
mock-api config
mock-api workspace list
mock-api workspace create [--name NAME] [--slug SLUG]
mock-api workspace select <slug>
mock-api api list [--workspace WORKSPACE_ID]
mock-api api create [--name NAME] [--slug SLUG]
mock-api api delete <api-id>
mock-api import <file> [--workspace WORKSPACE_ID] [--dry-run]See CLI README for complete documentation.
# From root
npm run test:all # Backend + Frontend
npm run test:e2e # Playwright E2E
# Individual
npm run test:backend # Jest unit + integration
npm run test:frontend # Vitest
npm run test:cli # CLI testscd backend
npm test # Run all tests
npm run test:watch # Watch mode
npm run test:cov # With coveragecd frontend
npm test # Run all tests
npm run test:watch # Watch mode
npm run test:coverage # With coverage# Ensure app is running (or use webServer config)
npx playwright test
npx playwright test --ui # UI mode
npx playwright show-report # View resultsAccess analytics at http://localhost:8080/analytics
- Request trends: Requests per day/week/month
- Top APIs: Most called mock APIs
- Top Endpoints: Most used endpoints
- Performance: Average response times
- Error rates: Failed requests tracking
- JWT Authentication: Secure user sessions
- API Keys: Programmatic access with scoped permissions
- Rate Limiting: Protect against abuse (100 requests/minute)
- Helmet: Security headers (CSP, HSTS, etc.)
- CORS: Configurable cross-origin policies
- Request Validation: JSON Schema enforcement
- Webhook Secrets: Sign webhook payloads for verification
Services:
- db (PostgreSQL 16) β localhost:5432
- redis (Redis 7) β localhost:6379
- api (NestJS backend) β localhost:3000
- web (Nginx + React) β localhost:8080docker compose up -d # Start detached
docker compose logs -f api # Follow API logs
docker compose exec api npm run prisma:studio # Prisma Studio
docker compose down -v # Stop and remove volumes
docker compose restart api # Restart backendPOST /auth/register # Register user
POST /auth/login # Login
GET /auth/api-keys # List API keys
POST /auth/api-keys # Create API key
GET /admin/workspaces # List workspaces
POST /admin/workspaces # Create workspace
PUT /admin/workspaces/:id # Update workspace
DELETE /admin/workspaces/:id # Delete workspace
GET /admin/webhooks # List webhooks
POST /admin/webhooks # Create webhook
PUT /admin/webhooks/:id # Update webhook
DELETE /admin/webhooks/:id # Delete webhook
GET /admin/analytics/summary # Analytics overview
GET /admin/analytics/requests # Request logs
ALL /mock/:apiSlug/* # REST mock
POST /mock-graphql/:apiSlug # GraphQL mock
Headers:
X-Workspace-Id: Specify workspace (or use?workspaceId=...)X-Webhook-Secret: For webhook verification
cd backend
npm run prisma:migrate # Create and apply migration
npm run prisma:migrate:deploy # Apply in production
npm run prisma:studio # Visual DB editor
npm run prisma:seed # Seed example dataBackend:
cd backend
npm run test # Run all tests
npm run test:watch # Watch mode
npm run test:coverage # Generate coverage report (80% threshold)
npm run test:e2e # Integration testsFrontend:
cd frontend
npm run test # Run all tests
npm run test:watch # Watch mode
npm run test:coverage # Generate coverage report (70% threshold)E2E Tests:
npm run test:e2e # Run Playwright testsCoverage Reports:
- Backend:
backend/coverage/lcov-report/index.html - Frontend:
frontend/coverage/index.html
# Backend
cd backend
npm run lint # ESLint
npm run format # Prettier
# Frontend
cd frontend
npm run lint # ESLintPrometheus Metrics:
# Access metrics endpoint
curl http://localhost:3000/metricsAvailable Metrics:
http_requests_total- Total HTTP requests by method, route, status, workspacehttp_request_duration_seconds- Request latency histogrammock_requests_total- Mock API requests by API slug, method, endpointwebhook_deliveries_total- Webhook delivery counts by event type and statuscache_hits_total/cache_misses_total- Cache performance- Node.js metrics (CPU, memory, event loop lag)
Grafana Dashboard:
# Request rate
rate(http_requests_total[5m])
# P95 latency
histogram_quantile(0.95, rate(http_request_duration_seconds_bucket[5m]))
# Webhook success rate
rate(webhook_deliveries_total{status="success"}[5m]) / rate(webhook_deliveries_total[5m])
Backend (.env):
# Database
DATABASE_URL=postgresql://mockapi:mockapi@localhost:5432/mockapi
# Redis
REDIS_HOST=localhost
REDIS_PORT=6379
# Auth
JWT_SECRET=your-super-secret-jwt-key
# Server
PORT=3000
NODE_ENV=production
# Cache
MOCK_API_CACHE_TTL_SECONDS=60
# Analytics
ANALYTICS_ENABLED=true
ANALYTICS_RETENTION_DAYS=90
# Rate Limiting
GLOBAL_RATE_LIMIT_RPM=100
WORKSPACE_RATE_LIMIT_RPM=500
# Webhooks
WEBHOOK_RETRY_ATTEMPTS=3
WEBHOOK_RETRY_DELAY_MS=1000Frontend (.env):
VITE_API_BASE_URL=http://localhost:3000Quick Deploy:
# Create secrets
cp k8s/secret.yaml.template k8s/secret.yaml
# Edit and add base64-encoded values
# Apply manifests
kubectl apply -f k8s/configmap.yaml
kubectl apply -f k8s/secret.yaml
kubectl apply -f k8s/backend-deployment.yaml
kubectl apply -f k8s/frontend-deployment.yaml
kubectl apply -f k8s/ingress.yaml
# Verify
kubectl get pods
kubectl logs -f deployment/mock-api-studio-backendFeatures:
- 2 replicas per service (auto-scaling ready)
- Health probes (liveness + readiness)
- Resource limits (CPU & memory)
- ConfigMap for non-sensitive config
- Secrets for DB and JWT
- Ingress with TLS support
Scaling:
kubectl scale deployment mock-api-studio-backend --replicas=5See k8s/README.md for full deployment guide.
GitHub Actions Workflow:
- β Automated testing on PR and push
- β Coverage enforcement (80% backend, 70% frontend)
- β Docker image builds
- β Codecov integration
- β Multi-stage builds with caching
Workflow File: .github/workflows/ci.yml
Triggers:
- Push to
mainordevelop - Pull requests to
mainordevelop
- Clean Architecture: Modules organized by domain (workspaces, webhooks, etc.)
- Dependency Injection: NestJS DI container for testability
- SOLID Principles: Single responsibility, interface segregation
- Caching Strategy: Redis for API definitions, configurable TTL, automatic invalidation
- Async Webhooks: Non-blocking event notifications with retry logic and exponential backoff
- Type Safety: Full TypeScript coverage (backend + frontend)
- React Context: State management for auth, workspace, and theme
- Protected Routes: HOC pattern for authenticated pages
- Observability: Prometheus metrics, structured logging, health checks
See CONTRIBUTING.md for development guidelines.
MIT
Built with:
- NestJS, React, Prisma, Docker
- Inspired by Postman, Mockoon, json-server
- Community feedback and contributions
Made with β€οΈ for developers who need reliable mock APIs