一个完整的Claude Code命令行工具的REST API包装器,提供同步和异步调用能力。
- 同步执行:直接调用Claude Code并返回结果
- 异步执行:支持后台任务队列处理
- 批量处理:一次性处理多个任务
- 工作流支持:复杂多步骤任务的编排执行
- 任务队列:内置任务管理器和队列系统
- 重试机制:自动重试失败的任务
- 错误处理:完善的错误处理和日志记录
- 速率限制:可配置的API调用限制
- 健康检查:服务健康状态监控
- 配置管理:灵活的环境变量配置
claude_code_api/
├── src/ # 源代码
│ └── claude_wrapper.py # Claude Code包装器核心实现
├── api/ # API服务
│ └── app.py # Flask应用和路由定义
├── config/ # 配置文件
│ └── config.py # 配置管理类
├── tests/ # 测试用例
│ ├── test_claude_wrapper.py # 包装器测试
│ └── test_api.py # API测试
├── logs/ # 日志文件目录
├── docs/ # 文档目录
├── requirements.txt # Python依赖
├── .env.example # 环境变量示例
├── Dockerfile # Docker配置
├── docker-compose.yml # Docker Compose配置
├── run.py # 启动脚本
└── README.md # 项目文档
git clone <repository-url>
cd claude_code_apipip install -r requirements.txt复制环境变量示例文件:
cp .env.example .env编辑 .env 文件,设置必要的配置:
# 必需配置
CLAUDE_API_KEY=your-claude-api-key-here
SECRET_KEY=your-secret-key-here
# 可选配置
API_HOST=0.0.0.0
API_PORT=5000
CLAUDE_DEFAULT_TIMEOUT=60
CLAUDE_MAX_RETRIES=3
RATE_LIMIT_PER_MINUTE=100
LOG_LEVEL=INFO# 检查Claude Code是否可用
claude --versionpython run.py# 使用Gunicorn
gunicorn --bind 0.0.0.0:5000 --workers 4 api.app:create_flask_app()
# 使用Docker
docker-compose up -dGET /health响应:
{
"status": "healthy",
"claude_code_available": true,
"timestamp": "2024-01-01T00:00:00",
"version": "claude version 1.0.0"
}GET /version响应:
{
"claude_code_version": "claude version 1.0.0",
"api_version": "1.0.0",
"timestamp": "2024-01-01T00:00:00"
}POST /api/claude-code
Content-Type: application/json
{
"prompt": "写一个Python函数计算斐波那契数列",
"options": {
"format": "json",
"model": "claude-3",
"max_tokens": 1000,
"temperature": 0.7
}
}响应:
{
"success": true,
"result": {
"status": "success",
"output": "def fibonacci(n): ...",
"error": "",
"return_code": 0,
"execution_time": 2.3,
"command": "claude code --api-key *** --prompt ...",
"success": true
},
"request_id": "uuid-here"
}POST /api/claude-code/async
Content-Type: application/json
{
"prompt": "分析这个Python代码的性能问题",
"options": {
"format": "markdown",
"timeout": 120
}
}响应:
{
"task_id": "uuid-here",
"status": "pending",
"message": "任务已提交,请使用task_id查询结果",
"request_id": "uuid-here"
}GET /api/claude-code/task/{task_id}响应:
{
"task_id": "uuid-here",
"status": "completed",
"created_at": "2024-01-01T00:00:00",
"updated_at": "2024-01-01T00:01:00",
"started_at": "2024-01-01T00:00:05",
"completed_at": "2024-01-01T00:01:00",
"result": {
"status": "success",
"output": "性能分析结果...",
"error": "",
"return_code": 0,
"execution_time": 55.2
},
"request_id": "uuid-here"
}POST /api/claude-code/batch
Content-Type: application/json
{
"tasks": [
{
"prompt": "写一个冒泡排序算法",
"options": {"format": "python"}
},
{
"prompt": "解释冒泡排序的时间复杂度",
"options": {"format": "markdown"}
}
],
"timeout": 60,
"max_retries": 3
}响应:
{
"success": true,
"total_tasks": 2,
"successful_tasks": 2,
"failed_tasks": 0,
"results": [
{
"status": "success",
"output": "def bubble_sort(...)",
"success": true
},
{
"status": "success",
"output": "冒泡排序的时间复杂度为...",
"success": true
}
],
"request_id": "uuid-here"
}POST /api/claude-code/workflow
Content-Type: application/json
{
"workflow": [
{
"name": "code_generation",
"prompt": "写一个快速排序算法",
"options": {"format": "python"},
"critical": true
},
{
"name": "code_analysis",
"prompt": "分析前面代码的时间复杂度和空间复杂度",
"options": {"format": "markdown"},
"use_context": true
},
{
"name": "optimization",
"prompt": "基于前面的分析,提供优化建议",
"options": {"format": "markdown"},
"use_context": true
}
]
}响应:
{
"success": true,
"total_steps": 3,
"completed_steps": 3,
"successful_steps": 3,
"failed_steps": 0,
"results": [
{
"step_name": "code_generation",
"step_number": 1,
"success": true,
"result": {
"status": "success",
"output": "def quick_sort(...)"
}
},
{
"step_name": "code_analysis",
"step_number": 2,
"success": true,
"result": {
"status": "success",
"output": "时间复杂度: O(n log n)..."
}
},
{
"step_name": "optimization",
"step_number": 3,
"success": true,
"result": {
"status": "success",
"output": "优化建议:..."
}
}
],
"final_context": {
"code_generation": "def quick_sort(...)",
"code_analysis": "时间复杂度: O(n log n)..."
},
"request_id": "uuid-here"
}GET /api/tasks?status=pending&limit=10&offset=0响应:
{
"tasks": [
{
"id": "uuid-here",
"status": "pending",
"created_at": "2024-01-01T00:00:00",
"updated_at": "2024-01-01T00:00:00"
}
],
"total": 1,
"limit": 10,
"offset": 0,
"request_id": "uuid-here"
}POST /api/tasks/cleanup
Content-Type: application/json
{
"days": 7
}响应:
{
"message": "已清理 7 天前的旧任务",
"request_id": "uuid-here"
}pytest# 测试Claude包装器
pytest tests/test_claude_wrapper.py
# 测试API
pytest tests/test_api.pypytest --cov=src --cov=api --cov-report=html| 变量名 | 默认值 | 说明 |
|---|---|---|
FLASK_ENV |
development |
运行环境 (development/production) |
API_HOST |
0.0.0.0 |
API服务监听地址 |
API_PORT |
5000 |
API服务端口 |
SECRET_KEY |
- | Flask应用密钥(生产环境必需) |
CLAUDE_API_KEY |
- | Claude API密钥 |
CLAUDE_DEFAULT_TIMEOUT |
60 |
默认超时时间(秒) |
CLAUDE_MAX_RETRIES |
3 |
最大重试次数 |
RATE_LIMIT_PER_MINUTE |
100 |
每分钟速率限制 |
LOG_LEVEL |
INFO |
日志级别 |
LOG_FILE |
logs/claude_api.log |
日志文件路径 |
| 选项名 | 类型 | 默认值 | 说明 |
|---|---|---|---|
format |
string | text |
输出格式 (text/json/markdown) |
model |
string | - | Claude模型名称 |
max_tokens |
int | - | 最大输出token数 |
temperature |
float | - | 温度参数 (0.0-1.0) |
timeout |
int | 60 |
请求超时时间(秒) |
max_retries |
int | 3 |
最大重试次数 |
output_file |
string | - | 输出文件路径 |
context_file |
string | - | 上下文文件路径 |
project_dir |
string | - | 项目目录路径 |
working_dir |
string | - | 工作目录路径 |
# 构建镜像
docker build -t claude-code-api .
# 运行容器
docker run -p 5000:5000 \
-e CLAUDE_API_KEY=your-api-key \
-e SECRET_KEY=your-secret-key \
claude-code-apidocker-compose up -d2024-01-01 12:00:00 INFO: Request GET /health completed,耗时: 0.003s
2024-01-01 12:00:01 INFO: 任务已添加到队列: uuid-here
2024-01-01 12:00:02 INFO: 任务完成: uuid-here, 状态: success
- 请求响应时间
- 任务执行成功率
- 并发任务数量
- 错误率和异常统计
200:成功202:异步任务已接受400:请求参数错误404:资源不存在429:速率限制500:服务器内部错误
{
"error": "Bad Request",
"message": "缺少必需的prompt参数",
"status_code": 400
}- API密钥保护:始终使用环境变量存储敏感信息
- 速率限制:配置适当的速率限制防止滥用
- 输入验证:验证所有用户输入
- CORS配置:根据需要配置跨域访问
- 日志脱敏:确保日志中不包含敏感信息
注意:使用此API前,请确保您已经安装并配置了Claude Code命令行工具,并且有有效的API密钥。