💡 前置阅读推荐:如果你还不了解Claude Code子代理的基础知识,强烈建议先阅读我的上一篇文章《Claude Code子代理完全指南:从0到1构建你的AI编程军团》,它会帮你理解子代理的运作机制和基础配置。
今天要分享的是我精心打磨的API开发子代理——这是专门为接口开发优化的配置,能让Claude Code像一个专业的API架构师一样设计和构建接口。
想象一下,API就像餐厅的菜单和点餐系统:
// 场景对比:创建一个获取用户信息的API
// ❌ 通用Claude可能给你的代码
app.get('/user', (req, res) => {
res.json({name: 'John'})
})
// 问题:没有认证、没有错误处理、没有文档、没有版本控制
// ✅ API子代理会给你的完整方案
/**
* @api {get} /api/v1/users/:id 获取用户信息
* @apiVersion 1.0.0
* @apiHeader {String} Authorization Bearer token
* @apiParam {String} id 用户ID
* @apiSuccess {Object} user 用户信息
* @apiError {Object} 404 用户不存在
*/
app.get('/api/v1/users/:id',
authenticate, // 认证中间件
validateParams, // 参数验证
rateLimit, // 速率限制
async (req, res) => {
try {
const user = await getUserById(req.params.id)
if (!user) {
return res.status(404).json({
error: 'USER_NOT_FOUND',
message: '用户不存在'
})
}
res.json({
data: user,
meta: { timestamp: newDate() }
})
} catch (error) {
handleError(error, res)
}
})
问题类型 | 具体表现 | API子代理的解决方案 |
|---|---|---|
接口混乱 | URL不统一、命名随意 | 自动遵循RESTful规范 |
文档缺失 | 没人知道怎么调用 | 自动生成OpenAPI文档 |
安全漏洞 | 谁都能调用 | 默认实现认证授权 |
版本地狱 | 改了就崩 | 版本控制策略 |
性能问题 | 响应慢、易崩溃 | 缓存、限流、优化 |
我提供两个版本,你可以根据需要选择:
---
name: api-developer
description: Design and build developer-friendly APIs with proper documentation, versioning, and security. Specializes in REST, GraphQL, and API gateway patterns. Use PROACTIVELY for API-first development and integration projects.
model: sonnet
---
---
名称: api开发专家
描述: 设计和构建开发者友好的API,包含完善的文档、版本控制和安全措施。
专精于REST、GraphQL和API网关模式。
在API优先开发和集成项目中主动使用。
模型: sonnet
---
---
name: api-developer
description: Design and build developer-friendly APIs with proper documentation, versioning, and security. Specializes in REST, GraphQL, and API gateway patterns. Use PROACTIVELY for API-first development and integration projects.
model: sonnet
---
You are an API development specialist focused on creating robust, well-documented, and developer-friendly APIs.
## API Expertise
- RESTful API design following Richardson Maturity Model
- GraphQL schema design and resolver optimization
- API versioning strategies and backward compatibility
- Rate limiting, throttling, and quota management
- API security (OAuth2, API keys, CORS, CSRF protection)
- Webhook design and event-driven integrations
- API gateway patterns and service composition
- Comprehensive documentation with interactive examples
## Design Standards
1. Consistent resource naming and HTTP verb usage
2. Proper HTTP status codes and error responses
3. Pagination, filtering, and sorting capabilities
4. Content negotiation and response formatting
5. Idempotent operations and safe retry mechanisms
6. Comprehensive validation and sanitization
7. Detailed logging for debugging and analytics
8. Performance optimization and caching headers
## Deliverables
- OpenAPI 3.0 specifications with examples
- Interactive API documentation (Swagger UI/Redoc)
- SDK generation scripts and client libraries
- Comprehensive test suites including contract testing
- Performance benchmarks and load testing results
- Security assessment and penetration testing reports
- Rate limiting and abuse prevention mechanisms
- Monitoring dashboards for API health and usage metrics
- Developer onboarding guides and quickstart tutorials
Create APIs that developers love to use. Focus on intuitive design, comprehensive documentation, and exceptional developer experience while maintaining security and performance standards.
---
name: api-developer
description: 设计和构建开发者友好的API,包含文档、版本控制和安全措施。专精REST、GraphQL和API网关。在API开发项目中主动使用。
model: sonnet
---
你是一位API开发专家,专注于创建健壮、文档完善、开发者友好的API。
## API专业技能
- 遵循Richardson成熟度模型的RESTful API设计
- GraphQL schema设计和解析器优化
- API版本策略和向后兼容性
- 速率限制、流量控制和配额管理
- API安全(OAuth2、API密钥、CORS、CSRF保护)
- Webhook设计和事件驱动集成
- API网关模式和服务组合
- 包含交互示例的完整文档
## 设计标准
1. 一致的资源命名和HTTP动词使用
2. 正确的HTTP状态码和错误响应
3. 分页、过滤和排序功能
4. 内容协商和响应格式化
5. 幂等操作和安全重试机制
6. 全面的验证和清理
7. 用于调试和分析的详细日志
8. 性能优化和缓存头
## 交付成果
- 带示例的OpenAPI 3.0规范
- 交互式API文档(Swagger UI/Redoc)
- SDK生成脚本和客户端库
- 包含契约测试的全面测试套件
- 性能基准和负载测试结果
- 安全评估和渗透测试报告
- 速率限制和防滥用机制
- API健康和使用指标的监控仪表板
- 开发者入门指南和快速启动教程
创建开发者喜爱使用的API。专注于直观设计、完整文档和卓越的开发者体验,同时保持安全和性能标准。
# 在Claude Code中输入
/agents
根据你的需求,选择英文版或中文注释版配置粘贴
API开发需要的权限:
建议选择 🔵 蓝色(代表接口连接),点击保存
输入指令:
创建一个完整的用户管理REST API,包括CRUD操作
API子代理输出:
// user.routes.js - 路由定义
const express = require('express');
const router = express.Router();
/**
* 用户管理API路由
* 基础路径: /api/v1/users
*/
// API版本和文档信息
const API_VERSION = 'v1';
const API_PREFIX = `/api/${API_VERSION}/users`;
// 中间件
const { authenticate } = require('../middleware/auth');
const { validate } = require('../middleware/validation');
const { rateLimit } = require('../middleware/rateLimit');
const { cache } = require('../middleware/cache');
// 验证规则
const userValidation = require('../validations/user.validation');
// 控制器
const userController = require('../controllers/user.controller');
/**
* @api {get} /api/v1/users 获取用户列表
* @apiName GetUsers
* @apiGroup User
* @apiVersion 1.0.0
*
* @apiHeader {String} Authorization Bearer token
*
* @apiQuery {Number} [page=1] 页码
* @apiQuery {Number} [limit=10] 每页数量
* @apiQuery {String} [sort=createdAt] 排序字段
* @apiQuery {String} [order=desc] 排序方向(asc/desc)
* @apiQuery {String} [search] 搜索关键词
* @apiQuery {String} [status] 用户状态筛选
*
* @apiSuccess {Object[]} data 用户列表
* @apiSuccess {Object} meta 分页信息
* @apiSuccess {Number} meta.total 总数
* @apiSuccess {Number} meta.page 当前页
* @apiSuccess {Number} meta.pages 总页数
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "data": [
* {
* "id": "123",
* "username": "john_doe",
* "email": "john@example.com",
* "role": "user",
* "status": "active",
* "createdAt": "2024-01-01T00:00:00Z"
* }
* ],
* "meta": {
* "total": 100,
* "page": 1,
* "pages": 10,
* "limit": 10
* },
* "links": {
* "self": "/api/v1/users?page=1",
* "next": "/api/v1/users?page=2",
* "last": "/api/v1/users?page=10"
* }
* }
*/
router.get('/',
authenticate,
rateLimit({ window: '1m', max: 100 }),
cache({ ttl: '5m' }),
validate(userValidation.getUsers),
userController.getUsers
);
/**
* @api {get} /api/v1/users/:id 获取单个用户
* @apiName GetUser
* @apiGroup User
* @apiVersion 1.0.0
*/
router.get('/:id',
authenticate,
rateLimit({ window: '1m', max: 200 }),
cache({ ttl: '10m', key: 'user:{id}' }),
validate(userValidation.getUser),
userController.getUser
);
/**
* @api {post} /api/v1/users 创建用户
* @apiName CreateUser
* @apiGroup User
* @apiVersion 1.0.0
*
* @apiBody {String} username 用户名(3-30字符)
* @apiBody {String} email 邮箱地址
* @apiBody {String} password 密码(最少8位)
* @apiBody {String} [role=user] 用户角色
*/
router.post('/',
authenticate,
rateLimit({ window: '1h', max: 10 }),
validate(userValidation.createUser),
userController.createUser
);
/**
* @api {put} /api/v1/users/:id 更新用户
* @apiName UpdateUser
* @apiGroup User
* @apiVersion 1.0.0
*/
router.put('/:id',
authenticate,
rateLimit({ window: '1m', max: 50 }),
validate(userValidation.updateUser),
userController.updateUser
);
/**
* @api {delete} /api/v1/users/:id 删除用户
* @apiName DeleteUser
* @apiGroup User
* @apiVersion 1.0.0
*/
router.delete('/:id',
authenticate,
rateLimit({ window: '1h', max: 20 }),
validate(userValidation.deleteUser),
userController.deleteUser
);
// 批量操作
router.post('/batch',
authenticate,
rateLimit({ window: '1h', max: 5 }),
validate(userValidation.batchOperation),
userController.batchOperation
);
module.exports = router;
// user.controller.js - 控制器实现
const userService = require('../services/user.service');
const { AppError } = require('../utils/errors');
const { logger } = require('../utils/logger');
class UserController {
/**
* 获取用户列表
*/
async getUsers(req, res, next) {
try {
// 构建查询参数
const queryOptions = {
page: parseInt(req.query.page) || 1,
limit: Math.min(parseInt(req.query.limit) || 10, 100),
sort: req.query.sort || 'createdAt',
order: req.query.order || 'desc',
search: req.query.search,
status: req.query.status,
fields: req.query.fields?.split(',')
};
// 调用服务层
const result = await userService.getUsers(queryOptions);
// 构建HATEOAS链接
const baseUrl = `${req.protocol}://${req.get('host')}${req.baseUrl}`;
const links = this.buildPaginationLinks(baseUrl, queryOptions, result.meta);
// 设置缓存头
res.set({
'X-Total-Count': result.meta.total,
'X-Page': result.meta.page,
'Cache-Control': 'private, max-age=300',
'ETag': `W/"users-${result.meta.page}-${result.meta.total}"`
});
// 返回响应
res.json({
success: true,
data: result.data,
meta: result.meta,
links
});
// 记录访问日志
logger.info('Users fetched', {
userId: req.user.id,
query: queryOptions,
resultCount: result.data.length
});
} catch (error) {
next(error);
}
}
/**
* 创建新用户
*/
async createUser(req, res, next) {
try {
// 开始事务
const user = await userService.createUser(req.body, {
createdBy: req.user.id
});
// 返回201状态码和Location头
res.status(201)
.location(`${req.baseUrl}/${user.id}`)
.json({
success: true,
message: '用户创建成功',
data: user
});
// 发送事件(用于其他服务订阅)
awaitthis.emitEvent('user.created', user);
logger.info('User created', {
newUserId: user.id,
createdBy: req.user.id
});
} catch (error) {
if (error.code === 'DUPLICATE_ENTRY') {
next(new AppError('用户已存在', 409));
} else {
next(error);
}
}
}
/**
* 构建分页链接(HATEOAS)
*/
buildPaginationLinks(baseUrl, query, meta) {
const links = {
self: `${baseUrl}?page=${meta.page}&limit=${meta.limit}`
};
if (meta.page > 1) {
links.first = `${baseUrl}?page=1&limit=${meta.limit}`;
links.prev = `${baseUrl}?page=${meta.page - 1}&limit=${meta.limit}`;
}
if (meta.page < meta.pages) {
links.next = `${baseUrl}?page=${meta.page + 1}&limit=${meta.limit}`;
links.last = `${baseUrl}?page=${meta.pages}&limit=${meta.limit}`;
}
return links;
}
}
module.exports = new UserController();
看看API子代理自动实现了什么:
输入:
为上面的用户API生成OpenAPI 3.0规范文档
输出:
openapi: 3.0.3
info:
title:用户管理API
version:1.0.0
description:完整的用户管理RESTfulAPI
contact:
name:APISupport
email:api@example.com
servers:
-url:https://api.example.com/api/v1
description:生产环境
-url:https://staging-api.example.com/api/v1
description:测试环境
paths:
/users:
get:
summary:获取用户列表
operationId:getUsers
tags:
-Users
security:
-bearerAuth:[]
parameters:
-name:page
in:query
schema:
type:integer
default:1
-name:limit
in:query
schema:
type:integer
default:10
maximum:100
responses:
'200':
description:成功获取用户列表
content:
application/json:
schema:
$ref:'#/components/schemas/UserListResponse'
components:
securitySchemes:
bearerAuth:
type:http
scheme:bearer
bearerFormat:JWT
schemas:
User:
type:object
required:
-username
-email
properties:
id:
type:string
format:uuid
username:
type:string
minLength:3
maxLength:30
## API Expertise
- GraphQL优先设计
- Apollo Server配置
- DataLoader批处理优化
- GraphQL订阅(WebSocket)
- Schema拼接和联邦
## Design Standards
- 服务间通信使用gRPC
- 事件驱动架构(Event Sourcing)
- 分布式追踪(OpenTelemetry)
- 熔断器模式(Circuit Breaker)
- API网关聚合
触发关键词:
在提示中明确指定:
生成Swagger 2.0格式的文档
生成Postman Collection
生成AsyncAPI规范(事件驱动)
可以!子代理会自动实现版本控制策略:
/api/v1/, /api/v2/API-Version: 1.0?version=1API子代理默认实现:
使用API子代理 vs 通用Claude的对比:
评估指标 | 通用Claude | API子代理 | 改进幅度 |
|---|---|---|---|
API规范遵守 | 40% | 98% | +145% |
文档完整性 | 20% | 95% | +375% |
安全措施 | 30% | 90% | +200% |
错误处理 | 50% | 95% | +90% |
开发者体验 | 一般 | 优秀 | 显著提升 |
这个API开发子代理的真正价值:
记住:好的API不仅能用,更要好用、安全、有文档。这个子代理帮你自动达到这些标准。
/agents现在就去配置你的API开发子代理,让每个接口都成为艺术品!🚀
#子代理 #ClaudeCode #AI #程序员 #前端达人