api-mock-server

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API 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
scripts
directory. Start it directly:
bash
undefined
服务器代码包含在本技能的
scripts
目录中,可直接启动:
bash
undefined

Start 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
/_api/routes
. The server must be running before calling these APIs.
所有管理API均以
/_api/routes
为前缀。调用这些API前必须确保服务器已运行。

Health Check Endpoint

健康检查端点

http
GET /_health
Response:
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/shutdown
Response:
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/routes
http://localhost:3000/_api/routes

1. List All Routes (GET)

1. 列出所有路由(GET)

http
GET /_api/routes
Response:
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/:key
Key format:
  • REST:
    METHOD:PATH
    (e.g.,
    GET:/api/user
    )
  • SSE:
    SSE:METHOD:PATH
    (e.g.,
    SSE:GET:/sse/chat
    )
Example:
http
GET /_api/routes/GET:/api/users
http
GET /_api/routes/:key
Key格式:
  • REST:
    METHOD:PATH
    (例如:
    GET:/api/user
  • SSE:
    SSE:METHOD:PATH
    (例如:
    SSE:GET:/sse/chat
示例:
http
GET /_api/routes/GET:/api/users

4. 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/:key
Example:
http
DELETE /_api/routes/GET:/api/users
http
DELETE /_api/routes/:key
示例:
http
DELETE /_api/routes/GET:/api/users

6. Clear All Routes (POST)

6. 清空所有路由(POST)

http
POST /_api/routes/clear
http
POST /_api/routes/clear

7. Export Routes (GET)

7. 导出路由(GET)

http
GET /_api/routes/export
Returns 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 TypeDescription
body
Match request body field
query
Match URL query parameter
header
Match request header
path
Match path parameter (for dynamic paths)
Operators:
equals
,
notEquals
,
contains
,
startsWith
,
endsWith
,
regex
,
exists
,
in
,
notIn
,
gt
,
gte
,
lt
,
lte
Example:
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" }
}
路由可根据请求条件返回不同响应:
条件类型描述
body
匹配请求体字段
query
匹配URL查询参数
header
匹配请求头
path
匹配路径参数(适用于动态路径)
操作符:
equals
,
notEquals
,
contains
,
startsWith
,
endsWith
,
regex
,
exists
,
in
,
notIn
,
gt
,
gte
,
lt
,
lte
示例:
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/shutdown
This 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
.env
file in
scripts/
directory:
PORT=3000
ADMIN_PASSWORD=admin123
scripts/
目录下创建
.env
文件:
PORT=3000
ADMIN_PASSWORD=admin123

Data Persistence

数据持久化

Dynamic routes are automatically saved to
scripts/data/routes.json
and loaded on server restart.
动态路由会自动保存到
scripts/data/routes.json
,并在服务器重启时加载。

Workflow for AI Agents

AI Agent工作流

  1. Check server health: Try
    GET /_health
    to verify server is running and healthy
  2. Check server status: Try
    GET /_api/routes
    to verify server is running
  3. Start server if needed: Run
    node .trae/skills/api-mock-server/scripts/server.js
  4. Create/Update routes: Use management API to configure mock endpoints
  5. Test endpoints: Call the mock endpoints to verify responses
  6. Shutdown server (optional): Use
    POST /_api/shutdown
    to gracefully stop the server
  7. Clean up: Use
    DELETE /_api/routes/:key
    or
    POST /_api/routes/clear
  1. 检查服务器健康状态:调用
    GET /_health
    验证服务器是否正常运行
  2. 检查服务器状态:调用
    GET /_api/routes
    验证服务器是否运行
  3. 按需启动服务器:运行
    node .trae/skills/api-mock-server/scripts/server.js
  4. 创建/更新路由:使用管理API配置模拟端点
  5. 测试端点:调用模拟端点验证响应
  6. 关闭服务器(可选):使用
    POST /_api/shutdown
    优雅停止服务器
  7. 清理:使用
    DELETE /_api/routes/:key
    POST /_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
    delay
    field to simulate network latency
  • Key format for route operations:
    METHOD:PATH
    or
    SSE:METHOD:PATH
  • The server is zero-dependency, using only Node.js built-in modules
  • 路由匹配顺序:动态SSE → 静态SSE → 静态REST → 动态REST → 404
  • 所有响应会自动添加CORS头
  • 使用
    delay
    字段模拟网络延迟
  • 路由操作的Key格式:
    METHOD:PATH
    SSE:METHOD:PATH
  • 该服务器为零依赖,仅使用Node.js内置模块