A lightweight and flexible mock server that uses JSON configuration to quickly create RESTful APIs.
- π Quick setup with JSON configuration
- π Support for GET, POST, PUT, DELETE methods
- π Automatic data persistence
- π Built-in pagination support
- π Customizable response schemas
- π Integration with Mock.js for powerful data mocking
- π€ File upload support
- π Real-time communication with WebSocket
- π‘ TypeScript support
# Using npm
npm install json-api-mocker
# Using yarn
yarn add json-api-mocker
# Using pnpm
pnpm add json-api-mocker
Create a data.json
file in your project root:
{
"server": {
"port": 8080,
"baseProxy": "/api"
},
"routes": [
{
"path": "/users",
"methods": {
"get": {
"type": "array",
"pagination": {
"enabled": true,
"pageSize": 10,
"totalCount": 100
},
"response": [
{
"id": 1,
"name": "John",
"age": 30,
"city": "New York"
}
]
}
}
},
{
"path": "/upload/avatar",
"methods": {
"post": {
"type": "object",
"mock": {
"enabled": true,
"template": {
"success": true,
"message": "Upload successful",
"data": {
"url": "@image('200x200')",
"filename": "@string(10).jpg",
"size": "@integer(1000, 1000000)"
}
}
}
}
}
}
]
}
There are several ways to start the mock server:
# Method 1: Using npx (Recommended)
npx json-api-mocker
# Method 2: Using npx with a custom config file
npx json-api-mocker ./custom-config.json
# Method 3: If installed globally
json-api-mocker
# Method 4: If installed as a project dependency
# Add this to your package.json scripts:
{
"scripts": {
"mock": "json-api-mocker"
}
}
# Then run:
npm run mock
Now your mock server is running at http://localhost:8080
!
You'll see output like this:
Mock Server is running:
- Address: http://localhost:8080
- Base Path: /api
Available APIs:
GET http://localhost:8080/api/users
POST http://localhost:8080/api/users
POST http://localhost:8080/api/upload/avatar
For detailed configuration options, please refer to CONFIG.md.
The server
section configures basic server settings:
{
"server": {
"port": 8080, // Server port number
"baseProxy": "/api" // Base path for all routes
}
}
Each route can support multiple HTTP methods:
{
"path": "/users", // Route path
"methods": {
"get": {
"type": "array", // Response type: "array" or "object"
"pagination": { // Optional pagination settings
"enabled": true,
"pageSize": 10,
"totalCount": 100
},
"response": [] // Response data
},
"post": {
"requestSchema": { // Request body validation schema
"name": "string",
"age": "number"
},
"response": {
"success": true
}
}
}
}
You can configure file upload endpoints in your data.json
:
{
"path": "/upload/avatar",
"methods": {
"post": {
"type": "object",
"mock": {
"enabled": true,
"template": {
"success": true,
"message": "Upload successful",
"data": {
"url": "@image('200x200')",
"filename": "@string(10).jpg",
"size": "@integer(1000, 1000000)"
}
}
}
}
}
}
# Upload single file
curl -X POST http://localhost:8080/api/upload/avatar \
-H "Content-Type: multipart/form-data" \
-F "avatar=@/path/to/your/image.jpg"
# Upload multiple files
curl -X POST http://localhost:8080/api/upload/images \
-H "Content-Type: multipart/form-data" \
-F "images=@/path/to/image1.jpg" \
-F "images=@/path/to/image2.jpg"
For detailed configuration options, please refer to CONFIG.md.
curl http://localhost:8080/api/users
curl http://localhost:8080/api/users/1
curl -X POST http://localhost:8080/api/users \
-H "Content-Type: application/json" \
-d '{"name":"Alice","age":25,"city":"Boston"}'
curl -X PUT http://localhost:8080/api/users/1 \
-H "Content-Type: application/json" \
-d '{"name":"Alice","age":26,"city":"Boston"}'
curl -X DELETE http://localhost:8080/api/users/1
# Get page 2 with 10 items per page
curl http://localhost:8080/api/users?page=2&pageSize=10
The server automatically adds these headers:
X-Total-Count
: Total number of items (for paginated responses)
You can use URL parameters in routes:
{
"path": "/users/:id/posts",
"methods": {
"get": {
"type": "array",
"response": []
}
}
}
Add schema validation for POST/PUT requests:
{
"requestSchema": {
"name": "string",
"age": "number",
"email": "string"
}
}
You can configure WebSocket endpoints in your data.json
:
{
"websocket": {
"enabled": true,
"path": "/ws",
"events": {
"realtime-data": {
"mock": {
"enabled": true,
"interval": 5000, // Send data every 5 seconds
"template": {
"timestamp": "@datetime",
"value|1-100": 1,
"status|1": ["normal", "warning", "error"]
}
}
},
"user-status": {
"mock": {
"enabled": true,
"template": {
"userId|+1": 1,
"status|1": ["online", "offline", "away"],
"lastActive": "@datetime"
}
}
}
}
}
}
// Connect to WebSocket server
const ws = new WebSocket('ws://localhost:8080/ws');
// Handle connection open
ws.onopen = () => {
console.log('Connected to WebSocket server');
// Request real-time data
ws.send(JSON.stringify({
event: 'realtime-data'
}));
};
// Handle incoming messages
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Received:', data);
// {
// event: 'realtime-data',
// data: {
// timestamp: '2024-01-01 12:00:00',
// value: 75,
// status: 'normal'
// }
// }
};
// Handle errors
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
// Handle connection close
ws.onclose = () => {
console.log('Disconnected from WebSocket server');
};
- Event-based communication
- Automatic data sending at specified intervals
- Mock.js template support for dynamic data
- Multiple event handlers
- 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 Β© [Xiong Haiyin]
- Express.js for the excellent web framework
- All our contributors and users