@vidhyasagarthakur/mockapi-cli
v1.0.1
Published
A CLI tool that generates a local mock server from an API contract JSON file
Maintainers
Readme
MockAPI CLI
A powerful CLI tool that generates a local mock server from an API contract (JSON/YAML). Perfect for frontend development when the backend isn't ready yet.
Installation
npm install -g @vidhyasagarthakur/mockapi-cliQuick Start
mockapi init # Create sample contract
mockapi start -c api-contract.json # Start mock serverCommands
mockapi start
mockapi start -c <contract> [options]| Option | Description |
|--------|-------------|
| -c, --contract <path> | Contract file (JSON/YAML) required |
| -p, --port <number> | Port (default: 3000) |
| -d, --delay <ms> | Response delay |
| -w, --watch | Auto-reload on file changes |
| -s, --stateful | Persist CRUD operations in memory |
| -v, --validate | Validate request bodies |
| --no-faker | Disable faker pattern processing |
| --no-dashboard | Disable web dashboard |
| --proxy <url> | Forward to real backend |
| --proxy-mode <mode> | fallback, mock-first, proxy-only |
| --response-mode <mode> | condition, sequential, random |
mockapi init
mockapi init [-o filename] [--yaml]mockapi import
mockapi import <openapi-spec> [-o filename] [--yaml] [--preview]mockapi record
Record real API responses and generate a contract:
mockapi record -t https://api.example.com [-p port] [-o output.json]| Option | Description |
|--------|-------------|
| -t, --target <url> | Target API URL to record required |
| -p, --port <number> | Proxy port (default: 3000) |
| -o, --output <file> | Output filename (default: recorded-contract.json) |
| -n, --name <name> | API name in contract |
| --yaml | Generate YAML format |
mockapi test
Run scenario tests against your mock server:
mockapi test -s scenarios.json [-b http://localhost:3000]| Option | Description |
|--------|-------------|
| -s, --scenarios <path> | Scenarios file required |
| -b, --base-url <url> | Server URL (default: http://localhost:3000) |
| -v, --verbose | Detailed output |
| --stop-on-failure | Stop on first failure |
Features
YAML Support
Contracts can be JSON or YAML:
name: My API
basePath: /api/v1
endpoints:
- method: GET
path: /users
response:
status: 200
body:
users: []Faker.js Integration
Generate realistic random data:
{
"body": {
"id": "faker:number.int({min:1,max:1000})",
"name": "faker:person.fullName",
"email": "faker:internet.email",
"avatar": "faker:image.avatar"
}
}| Pattern | Example Output |
|---------|---------------|
| faker:person.fullName | "John Doe" |
| faker:internet.email | "[email protected]" |
| faker:number.int({min:1,max:100}) | 42 |
| faker:date.recent | "2026-03-08T..." |
| faker:lorem.paragraph | "Lorem ipsum..." |
| faker:company.name | "Acme Corp" |
| faker:location.city | "San Francisco" |
| faker:helpers.arrayElement(["a","b"]) | "a" or "b" |
Multiple Responses
Define conditional responses per endpoint:
{
"method": "GET",
"path": "/users",
"responses": [
{
"status": 200,
"body": { "users": [...], "total": 10 },
"when": { "query": { "status": "active" } }
},
{
"status": 200,
"body": { "users": [], "total": 0 },
"when": { "query": { "status": "inactive" } }
},
{
"status": 200,
"body": { "users": [...] }
}
]
}Selection methods:
?_response=0- Force specific response by indexX-Mock-Response: 1- Via header--response-mode sequential- Rotate through responses--response-mode random- Random selection
Auth Simulation
Global auth in contract:
{
"auth": {
"type": "bearer",
"tokens": ["dev-token-123", "test-token"]
},
"endpoints": [
{
"method": "GET",
"path": "/users",
"auth": false
},
{
"method": "POST",
"path": "/users"
}
]
}Auth types:
// Bearer token
{ "type": "bearer", "tokens": ["token1", "token2"] }
// API Key (header)
{ "type": "apiKey", "header": "X-API-Key", "keys": ["key1"] }
// API Key (query param)
{ "type": "apiKey", "query": "api_key", "keys": ["key1"] }
// Basic auth
{ "type": "basic", "users": [{ "username": "admin", "password": "secret" }] }Endpoints inherit global auth. Use "auth": false to make public.
Stateful Mode
Enable with -s or --stateful:
# POST creates new records
curl -X POST http://localhost:3000/api/v1/users \
-d '{"name":"John"}'
# GET returns updated data
curl http://localhost:3000/api/v1/users
# DELETE removes records
curl -X DELETE http://localhost:3000/api/v1/users/1Proxy Mode
Forward requests to real backend:
# Try backend first, fall back to mock
mockapi start -c contract.json --proxy https://api.example.com
# Use mock for defined endpoints, proxy others
mockapi start -c contract.json --proxy https://api.example.com --proxy-mode mock-first
# Forward everything (no mocking)
mockapi start -c contract.json --proxy https://api.example.com --proxy-mode proxy-onlyRequest Validation
Enable with -v or --validate:
{
"method": "POST",
"path": "/users",
"requestBody": {
"name": { "type": "string", "required": true },
"email": { "type": "string", "required": true },
"age": "number"
}
}Returns 400 with details on validation failure.
OpenAPI Import
mockapi import openapi.yaml -o contract.json
mockapi import swagger.json --previewConverts OpenAPI 3.x / Swagger 2.x specs to MockAPI format with faker patterns.
Web Dashboard
Access the built-in dashboard at http://localhost:3000/_mockapi when the server is running:
- View all registered endpoints
- Monitor request history in real-time
- Test endpoints directly from browser
- View and edit contract (live reload)
Disable with --no-dashboard.
Recording Mode
Record real API responses to generate contracts:
# Start recording proxy
mockapi record -t https://api.example.com -p 3001
# Make requests through the proxy
curl http://localhost:3001/api/users
curl -X POST http://localhost:3001/api/users -d '{"name":"John"}'
# Press Ctrl+C to save contractThe generated contract includes:
- All recorded endpoints with methods and paths
- Response bodies and status codes
- Inferred query/path parameters
- Multiple response variants per endpoint
WebSocket Mocking
Mock WebSocket connections in your contract:
{
"websockets": [
{
"path": "/ws/chat",
"onConnect": {
"type": "welcome",
"message": "Connected to chat"
},
"onMessage": [
{
"when": { "type": "ping" },
"respond": { "type": "pong" }
},
{
"when": { "type": "subscribe" },
"respond": { "type": "subscribed", "channel": "$data.channel" }
}
],
"sequence": [
{ "delay": 5000, "emit": { "type": "heartbeat" } },
{ "delay": 10000, "emit": { "type": "update", "data": "faker:lorem.sentence" }, "repeat": 30000 }
]
}
]
}Features:
onConnect: Message sent when client connectsonMessage: Handlers for incoming messages with conditionssequence: Scheduled messages with delays and repeats- Template variables:
$data.fieldreferences incoming message fields - Faker patterns work in WebSocket responses
Scenario Testing
Define and run test scenarios:
{
"name": "User CRUD workflow",
"baseUrl": "http://localhost:3000",
"variables": {
"authToken": "Bearer test-token"
},
"steps": [
{
"name": "Create user",
"request": {
"method": "POST",
"path": "/api/v1/users",
"headers": { "Authorization": "$authToken" },
"body": { "name": "John", "email": "[email protected]" }
},
"expect": {
"status": 201,
"body": {
"id": { "$exists": true },
"name": "John"
}
},
"extract": {
"userId": "$.id"
}
},
{
"name": "Get created user",
"request": {
"method": "GET",
"path": "/api/v1/users/$userId"
},
"expect": {
"status": 200,
"body": { "name": "John" }
}
}
]
}Assertion matchers:
| Matcher | Example | Description |
|---------|---------|-------------|
| $exists | { "$exists": true } | Field exists |
| $type | { "$type": "string" } | Type check |
| $contains | { "$contains": "foo" } | String contains |
| $regex | { "$regex": "^[A-Z]" } | Regex match |
| $gt/$gte | { "$gt": 0 } | Greater than |
| $lt/$lte | { "$lt": 100 } | Less than |
| $length | { "$length": 5 } | Array/string length |
Variable extraction:
- Use
extractto save response values for later steps - Reference with
$variableNamein subsequent requests
Contract Schema
{
"name": "API Name",
"basePath": "/api/v1",
"auth": { "type": "bearer", "tokens": ["..."] },
"endpoints": [
{
"method": "GET|POST|PUT|PATCH|DELETE",
"path": "/resource/:id",
"description": "Description",
"auth": false,
"queryParams": [{ "name": "page", "type": "number" }],
"pathParams": [{ "name": "id", "type": "number", "required": true }],
"requestBody": { "field": { "type": "string", "required": true } },
"response": { "status": 200, "body": {...}, "headers": {...} },
"responses": [
{ "status": 200, "body": {...}, "when": { "query": {...} } }
]
}
]
}License
MIT
