api-mock-server
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Mock Server Skill
API Mock Server 技能
A lightweight, zero-dependency API Mock Server for frontend development and testing. This skill enables AI Agents to manage mock APIs programmatically.
这是一款轻量、零依赖的API Mock Server,适用于前端开发与测试。该技能支持AI Agent以编程方式管理模拟API。
Quick Start
快速开始
Start the Server
启动服务器
The server code is included in this skill's directory. Start it directly:
scriptsbash
undefined服务器代码包含在本技能的目录中,可直接启动:
scriptsbash
undefinedStart server from skill directory (default port: 3000)
从技能目录启动服务器(默认端口:3000)
node /scripts/server.js
node /scripts/server.js
Or with custom port
或使用自定义端口
node /scripts/server.js
After startup, access:
- **Admin Panel**: `http://localhost:3000/`
- **API List**: `http://localhost:3000/_list`
- **Health Check**: `http://localhost:3000/_health`node /scripts/server.js
启动后,访问:
- **管理面板**:`http://localhost:3000/`
- **API列表**:`http://localhost:3000/_list`
- **健康检查**:`http://localhost:3000/_health`Management API Endpoints
管理API端点
All management APIs are prefixed with . The server must be running before calling these APIs.
/_api/routes所有管理API均以为前缀。调用这些API前必须确保服务器已运行。
/_api/routesHealth Check Endpoint
健康检查端点
http
GET /_healthResponse:
json
{
"status": "ok",
"timestamp": 1773384296000,
"uptime": 123.456
}Use this endpoint to check if the server is running and healthy.
http
GET /_health响应:
json
{
"status": "ok",
"timestamp": 1773384296000,
"uptime": 123.456
}使用此端点检查服务器是否正常运行。
Shutdown Server Endpoint
关闭服务器端点
http
POST /_api/shutdownResponse:
json
{
"success": true,
"message": "Server shutting down..."
}Use this endpoint to gracefully shutdown the server. This endpoint requires authentication if admin password is enabled.
Note: After calling this endpoint, the server will close and the process will exit.
http
POST /_api/shutdown响应:
json
{
"success": true,
"message": "Server shutting down..."
}使用此端点优雅关闭服务器。若启用了管理员密码,此端点需要身份验证。
注意: 调用此端点后,服务器将关闭并退出进程。
Base URL
基础URL
http://localhost:3000/_api/routeshttp://localhost:3000/_api/routes1. List All Routes (GET)
1. 列出所有路由(GET)
http
GET /_api/routesResponse:
json
{
"routes": [
{
"path": "/api/user",
"method": "GET",
"delay": 500,
"response": { "code": 200, "data": {} },
"createdAt": 1772527195265,
"updatedAt": 1772527195265
}
]
}http
GET /_api/routes响应:
json
{
"routes": [
{
"path": "/api/user",
"method": "GET",
"delay": 500,
"response": { "code": 200, "data": {} },
"createdAt": 1772527195265,
"updatedAt": 1772527195265
}
]
}2. Create Route (POST)
2. 创建路由(POST)
http
POST /_api/routes
Content-Type: application/json
{
"path": "/api/users",
"method": "GET",
"delay": 200,
"response": {
"code": 200,
"message": "success",
"data": [{ "id": 1, "name": "John" }]
}
}Response: Returns the created route object.
http
POST /_api/routes
Content-Type: application/json
{
"path": "/api/users",
"method": "GET",
"delay": 200,
"response": {
"code": 200,
"message": "success",
"data": [{ "id": 1, "name": "John" }]
}
}响应: 返回创建的路由对象。
3. Get Single Route (GET)
3. 获取单个路由(GET)
http
GET /_api/routes/:keyKey format:
- REST: (e.g.,
METHOD:PATH)GET:/api/user - SSE: (e.g.,
SSE:METHOD:PATH)SSE:GET:/sse/chat
Example:
http
GET /_api/routes/GET:/api/usershttp
GET /_api/routes/:keyKey格式:
- REST: (例如:
METHOD:PATH)GET:/api/user - SSE: (例如:
SSE:METHOD:PATH)SSE:GET:/sse/chat
示例:
http
GET /_api/routes/GET:/api/users4. Update Route (PUT)
4. 更新路由(PUT)
http
PUT /_api/routes/:key
Content-Type: application/json
{
"delay": 1000,
"response": {
"code": 200,
"data": [{ "id": 1, "name": "Updated" }]
}
}http
PUT /_api/routes/:key
Content-Type: application/json
{
"delay": 1000,
"response": {
"code": 200,
"data": [{ "id": 1, "name": "Updated" }]
}
}5. Delete Route (DELETE)
5. 删除路由(DELETE)
http
DELETE /_api/routes/:keyExample:
http
DELETE /_api/routes/GET:/api/usershttp
DELETE /_api/routes/:key示例:
http
DELETE /_api/routes/GET:/api/users6. Clear All Routes (POST)
6. 清空所有路由(POST)
http
POST /_api/routes/clearhttp
POST /_api/routes/clear7. Export Routes (GET)
7. 导出路由(GET)
http
GET /_api/routes/exportReturns all routes as JSON for backup.
http
GET /_api/routes/export返回所有路由的JSON格式数据,用于备份。
8. Import Routes (POST)
8. 导入路由(POST)
http
POST /_api/routes/import
Content-Type: application/json
{
"routes": [
{
"path": "/api/imported",
"method": "GET",
"response": { "code": 200 }
}
]
}http
POST /_api/routes/import
Content-Type: application/json
{
"routes": [
{
"path": "/api/imported",
"method": "GET",
"response": { "code": 200 }
}
]
}Route Configuration Schema
路由配置Schema
REST API Route
REST API路由
json
{
"path": "/api/example",
"method": "GET",
"delay": 0,
"headers": { "X-Custom": "value" },
"response": {
"code": 200,
"message": "success",
"data": {}
},
"conditions": [
{
"match": {
"body.action": { "operator": "equals", "value": "login" }
},
"response": { "code": 200, "data": { "token": "xxx" } }
}
]
}json
{
"path": "/api/example",
"method": "GET",
"delay": 0,
"headers": { "X-Custom": "value" },
"response": {
"code": 200,
"message": "success",
"data": {}
},
"conditions": [
{
"match": {
"body.action": { "operator": "equals", "value": "login" }
},
"response": { "code": 200, "data": { "token": "xxx" } }
}
]
}SSE Route
SSE路由
json
{
"path": "/sse/stream",
"method": "GET",
"type": "sse",
"delay": 0,
"interval": 100,
"repeat": false,
"events": [
{ "data": "{\"type\":\"start\"}" },
{ "data": "{\"type\":\"message\",\"content\":\"Hello\"}" },
{ "data": "{\"type\":\"end\"}" }
]
}json
{
"path": "/sse/stream",
"method": "GET",
"type": "sse",
"delay": 0,
"interval": 100,
"repeat": false,
"events": [
{ "data": "{\"type\":\"start\"}" },
{ "data": "{\"type\":\"message\",\"content\":\"Hello\"}" },
{ "data": "{\"type\":\"end\"}" }
]
}Condition Matching
条件匹配
Routes can return different responses based on request conditions:
| Condition Type | Description |
|---|---|
| Match request body field |
| Match URL query parameter |
| Match request header |
| Match path parameter (for dynamic paths) |
Operators: , , , , , , , , , , , ,
equalsnotEqualscontainsstartsWithendsWithregexexistsinnotIngtgteltlteExample:
json
{
"path": "/api/order",
"method": "POST",
"conditions": [
{
"match": {
"body.status": { "operator": "equals", "value": "pending" }
},
"response": { "code": 200, "data": { "approved": false } }
},
{
"match": {
"body.status": { "operator": "equals", "value": "approved" }
},
"response": { "code": 200, "data": { "approved": true } }
}
],
"response": { "code": 400, "message": "Unknown status" }
}路由可根据请求条件返回不同响应:
| 条件类型 | 描述 |
|---|---|
| 匹配请求体字段 |
| 匹配URL查询参数 |
| 匹配请求头 |
| 匹配路径参数(适用于动态路径) |
操作符: , , , , , , , , , , , ,
equalsnotEqualscontainsstartsWithendsWithregexexistsinnotIngtgteltlte示例:
json
{
"path": "/api/order",
"method": "POST",
"conditions": [
{
"match": {
"body.status": { "operator": "equals", "value": "pending" }
},
"response": { "code": 200, "data": { "approved": false } }
},
{
"match": {
"body.status": { "operator": "equals", "value": "approved" }
},
"response": { "code": 200, "data": { "approved": true } }
}
],
"response": { "code": 400, "message": "Unknown status" }
}Common Use Cases
常见使用场景
1. Quick Mock API Creation
1. 快速创建模拟API
bash
curl -X POST http://localhost:3000/_api/routes \
-H "Content-Type: application/json" \
-d '{"path":"/api/products","method":"GET","response":{"code":200,"data":[{"id":1,"name":"Product A"}]}}'bash
curl -X POST http://localhost:3000/_api/routes \
-H "Content-Type: application/json" \
-d '{"path":"/api/products","method":"GET","response":{"code":200,"data":[{"id":1,"name":"Product A"}]}}'2. Mock Login API
2. 模拟登录API
bash
curl -X POST http://localhost:3000/_api/routes \
-H "Content-Type: application/json" \
-d '{
"path": "/api/login",
"method": "POST",
"delay": 500,
"response": {
"code": 200,
"data": { "token": "mock-jwt-token", "expiresIn": 3600 }
}
}'bash
curl -X POST http://localhost:3000/_api/routes \
-H "Content-Type: application/json" \
-d '{
"path": "/api/login",
"method": "POST",
"delay": 500,
"response": {
"code": 200,
"data": { "token": "mock-jwt-token", "expiresIn": 3600 }
}
}'3. Mock Paginated List
3. 模拟分页列表
bash
curl -X POST http://localhost:3000/_api/routes \
-H "Content-Type: application/json" \
-d '{
"path": "/api/users",
"method": "GET",
"response": {
"code": 200,
"data": {
"list": [{"id":1,"name":"User1"},{"id":2,"name":"User2"}],
"total": 100,
"page": 1,
"pageSize": 10
}
}
}'bash
curl -X POST http://localhost:3000/_api/routes \
-H "Content-Type: application/json" \
-d '{
"path": "/api/users",
"method": "GET",
"response": {
"code": 200,
"data": {
"list": [{"id":1,"name":"User1"},{"id":2,"name":"User2"}],
"total": 100,
"page": 1,
"pageSize": 10
}
}
}'4. Mock Error Response
4. 模拟错误响应
bash
curl -X POST http://localhost:3000/_api/routes \
-H "Content-Type: application/json" \
-d '{
"path": "/api/error",
"method": "GET",
"response": {
"code": 500,
"message": "Internal Server Error"
}
}'bash
curl -X POST http://localhost:3000/_api/routes \
-H "Content-Type: application/json" \
-d '{
"path": "/api/error",
"method": "GET",
"response": {
"code": 500,
"message": "Internal Server Error"
}
}'5. Create SSE Stream
5. 创建SSE流
bash
curl -X POST http://localhost:3000/_api/routes \
-H "Content-Type: application/json" \
-d '{
"path": "/sse/notifications",
"method": "GET",
"type": "sse",
"interval": 1000,
"repeat": true,
"events": [
{"data": "{\"type\":\"notification\",\"message\":\"New message\"}"}
]
}'bash
curl -X POST http://localhost:3000/_api/routes \
-H "Content-Type: application/json" \
-d '{
"path": "/sse/notifications",
"method": "GET",
"type": "sse",
"interval": 1000,
"repeat": true,
"events": [
{"data": "{\"type\":\"notification\",\"message\":\"New message\"}"}
]
}'6. Shutdown Server
6. 关闭服务器
bash
curl -X POST http://localhost:3000/_api/shutdownThis will gracefully shutdown the server. If admin password is enabled, you need to authenticate first.
bash
curl -X POST http://localhost:3000/_api/shutdown这将优雅关闭服务器。若启用了管理员密码,您需要先进行身份验证。
Programmatic Usage (Node.js)
编程式使用(Node.js)
The skill includes a helper module for programmatic control:
javascript
const MockServer = require('./.trae/skills/api-mock-server/scripts/server.js');
// Or use the API client
const baseUrl = 'http://localhost:3000';
// Create route
await fetch(`${baseUrl}/_api/routes`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
path: '/api/test',
method: 'GET',
response: { code: 200, data: { message: 'Hello' } }
})
});
// List routes
const res = await fetch(`${baseUrl}/_api/routes`);
const { routes } = await res.json();
// Delete route
await fetch(`${baseUrl}/_api/routes/GET:/api/test`, { method: 'DELETE' });该技能包含一个辅助模块,用于编程式控制:
javascript
const MockServer = require('./.trae/skills/api-mock-server/scripts/server.js');
// 或使用API客户端
const baseUrl = 'http://localhost:3000';
// 创建路由
await fetch(`${baseUrl}/_api/routes`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
path: '/api/test',
method: 'GET',
response: { code: 200, data: { message: 'Hello' } }
})
});
// 列出路由
const res = await fetch(`${baseUrl}/_api/routes`);
const { routes } = await res.json();
// 删除路由
await fetch(`${baseUrl}/_api/routes/GET:/api/test`, { method: 'DELETE' });Static Configuration Files
静态配置文件
For permanent routes, edit configuration files in :
scripts/config/- REST APIs:
scripts/config/interfaces.js - SSE APIs:
scripts/config/sse-interfaces.js
Changes require server restart.
如需永久路由,请编辑目录下的配置文件:
scripts/config/- REST API:
scripts/config/interfaces.js - SSE API:
scripts/config/sse-interfaces.js
修改后需要重启服务器。
Environment Variables
环境变量
Create file in directory:
.envscripts/PORT=3000
ADMIN_PASSWORD=admin123在目录下创建文件:
scripts/.envPORT=3000
ADMIN_PASSWORD=admin123Data Persistence
数据持久化
Dynamic routes are automatically saved to and loaded on server restart.
scripts/data/routes.json动态路由会自动保存到,并在服务器重启时加载。
scripts/data/routes.jsonWorkflow for AI Agents
AI Agent工作流
- Check server health: Try to verify server is running and healthy
GET /_health - Check server status: Try to verify server is running
GET /_api/routes - Start server if needed: Run
node .trae/skills/api-mock-server/scripts/server.js - Create/Update routes: Use management API to configure mock endpoints
- Test endpoints: Call the mock endpoints to verify responses
- Shutdown server (optional): Use to gracefully stop the server
POST /_api/shutdown - Clean up: Use or
DELETE /_api/routes/:keyPOST /_api/routes/clear
- 检查服务器健康状态:调用验证服务器是否正常运行
GET /_health - 检查服务器状态:调用验证服务器是否运行
GET /_api/routes - 按需启动服务器:运行
node .trae/skills/api-mock-server/scripts/server.js - 创建/更新路由:使用管理API配置模拟端点
- 测试端点:调用模拟端点验证响应
- 关闭服务器(可选):使用优雅停止服务器
POST /_api/shutdown - 清理:使用或
DELETE /_api/routes/:keyPOST /_api/routes/clear
Notes
注意事项
- Routes are matched in order: Dynamic SSE → Static SSE → Static REST → Dynamic REST → 404
- CORS headers are automatically added to all responses
- Use field to simulate network latency
delay - Key format for route operations: or
METHOD:PATHSSE:METHOD:PATH - The server is zero-dependency, using only Node.js built-in modules
- 路由匹配顺序:动态SSE → 静态SSE → 静态REST → 动态REST → 404
- 所有响应会自动添加CORS头
- 使用字段模拟网络延迟
delay - 路由操作的Key格式:或
METHOD:PATHSSE:METHOD:PATH - 该服务器为零依赖,仅使用Node.js内置模块