api-designer
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAPI Designer
API 设计专家
Expert in designing REST and GraphQL APIs that are robust, scalable, and maintainable.
擅长设计健壮、可扩展、可维护的REST和GraphQL API。
When This Skill Activates
技能触发场景
Activates when you:
- Design a new API
- Review API design
- Improve existing API
- Create API specifications
当你需要完成以下操作时触发本技能:
- 设计全新API
- 评审API设计方案
- 优化现有API
- 编写API规范
REST API Design Principles
REST API 设计原则
1. Resource-Oriented Design
1. 面向资源设计
Good:
GET /users # List users
POST /users # Create user
GET /users/{id} # Get specific user
PATCH /users/{id} # Update user
DELETE /users/{id} # Delete userAvoid:
POST /getUsers # Should be GET
POST /users/create # Redundant
GET /users/get/{id} # Redundant正确示例:
GET /users # 获取用户列表
POST /users # 创建用户
GET /users/{id} # 获取指定用户
PATCH /users/{id} # 更新用户
DELETE /users/{id} # 删除用户应避免的写法:
POST /getUsers # 应使用GET
POST /users/create # 冗余写法
GET /users/get/{id} # 冗余写法2. HTTP Methods
2. HTTP 方法规范
| Method | Safe | Idempotent | Purpose |
|---|---|---|---|
| GET | ✓ | ✓ | Read resource |
| POST | ✗ | ✗ | Create resource |
| PUT | ✗ | ✓ | Replace resource |
| PATCH | ✗ | ✗ | Update resource |
| DELETE | ✗ | ✓ | Delete resource |
| 方法 | 安全 | 幂等 | 用途 |
|---|---|---|---|
| GET | ✓ | ✓ | 读取资源 |
| POST | ✗ | ✗ | 创建资源 |
| PUT | ✗ | ✓ | 替换资源 |
| PATCH | ✗ | ✗ | 更新资源 |
| DELETE | ✗ | ✓ | 删除资源 |
3. Status Codes
3. 状态码规范
| Code | Meaning | Usage |
|---|---|---|
| 200 | OK | Successful GET, PATCH, DELETE |
| 201 | Created | Successful POST |
| 204 | No Content | Successful DELETE with no body |
| 400 | Bad Request | Invalid input |
| 401 | Unauthorized | Missing or invalid auth |
| 403 | Forbidden | Authenticated but not authorized |
| 404 | Not Found | Resource doesn't exist |
| 409 | Conflict | Resource already exists |
| 422 | Unprocessable | Valid syntax but semantic errors |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Server error |
| 状态码 | 含义 | 适用场景 |
|---|---|---|
| 200 | 请求成功 | GET、PATCH、DELETE请求执行成功 |
| 201 | 已创建 | POST请求执行成功 |
| 204 | 无内容 | DELETE请求执行成功且无返回体 |
| 400 | 请求错误 | 输入参数非法 |
| 401 | 未认证 | 缺失或使用无效的认证信息 |
| 403 | 无权限 | 已认证但无对应操作权限 |
| 404 | 未找到 | 资源不存在 |
| 409 | 冲突 | 资源已存在 |
| 422 | 无法处理请求 | 语法合法但存在语义错误 |
| 429 | 请求过多 | 超出限流阈值 |
| 500 | 服务内部错误 | 服务端异常 |
4. Naming Conventions
4. 命名规范
- URLs: kebab-case ()
/user-preferences - JSON: camelCase ()
{"userId": "123"} - Query params: snake_case or camelCase ()
?page_size=10
- URL: 使用kebab-case(短横线命名法,如 )
/user-preferences - JSON: 使用camelCase(小驼峰命名法,如 )
{"userId": "123"} - 查询参数: 使用snake_case(下划线命名法)或camelCase(如 )
?page_size=10
5. Pagination
5. 分页规范
http
GET /users?page=1&page_size=20
Response:
{
"data": [...],
"pagination": {
"page": 1,
"page_size": 20,
"total": 100,
"total_pages": 5
}
}http
GET /users?page=1&page_size=20
返回示例:
{
"data": [...],
"pagination": {
"page": 1,
"page_size": 20,
"total": 100,
"total_pages": 5
}
}6. Filtering and Sorting
6. 过滤与排序规范
http
GET /users?status=active&sort=-created_at,namehttp
GET /users?status=active&sort=-created_at,name-created_at = descending
-created_at = 按创建时间倒序
name = ascending
name = 按名称正序
undefinedundefinedGraphQL API Design
GraphQL API 设计
Schema Design
Schema 设计规范
graphql
type Query {
user(id: ID!): User
users(limit: Int, offset: Int): UserConnection!
}
type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
updateUser(id: ID!, input: UpdateUserInput!): UpdateUserPayload!
}
type User {
id: ID!
email: String!
profile: Profile
posts(first: Int, after: String): PostConnection!
}
type UserConnection {
edges: [UserEdge!]!
pageInfo: PageInfo!
}
type UserEdge {
node: User!
cursor: String!
}
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}graphql
type Query {
user(id: ID!): User
users(limit: Int, offset: Int): UserConnection!
}
type Mutation {
createUser(input: CreateUserInput!): CreateUserPayload!
updateUser(id: ID!, input: UpdateUserInput!): UpdateUserPayload!
}
type User {
id: ID!
email: String!
profile: Profile
posts(first: Int, after: String): PostConnection!
}
type UserConnection {
edges: [UserEdge!]!
pageInfo: PageInfo!
}
type UserEdge {
node: User!
cursor: String!
}
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}Best Practices
最佳实践
- Nullability: Default to non-null, nullable only when appropriate
- Connections: Use cursor-based pagination for lists
- Payloads: Use mutation payloads for consistent error handling
- Descriptions: Document all types and fields
- 空值处理: 默认设为非空,仅在合理场景下允许为空
- 分页: 列表使用基于游标分页的Connection规范
- 变更负载: Mutation操作使用统一负载结构实现一致的错误处理
- 文档: 为所有类型和字段添加描述说明
API Versioning
API 版本控制
Approaches
实现方案
URL Versioning (Recommended):
/api/v1/users
/api/v2/usersHeader Versioning:
GET /users
Accept: application/vnd.myapi.v2+jsonURL 版本控制(推荐):
/api/v1/users
/api/v2/users请求头版本控制:
GET /users
Accept: application/vnd.myapi.v2+jsonVersioning Guidelines
版本控制规范
- Start with v1
- Maintain backwards compatibility when possible
- Deprecate old versions with notice
- Document breaking changes
- 初始版本从v1开始
- 尽可能保持向后兼容
- 废弃旧版本前提前发出通知
- 记录所有破坏性变更
Authentication & Authorization
认证与授权
Authentication Methods
认证方式
- JWT Bearer Token
http
Authorization: Bearer <token>- API Key
http
X-API-Key: <key>- OAuth 2.0
http
Authorization: Bearer <access_token>- JWT Bearer Token
http
Authorization: Bearer <token>- API Key
http
X-API-Key: <key>- OAuth 2.0
http
Authorization: Bearer <access_token>Authorization
授权规范
- Use roles/permissions
- Document required permissions per endpoint
- Return 403 for authorization failures
- 使用角色/权限体系
- 为每个端点标注所需权限
- 授权失败时返回403状态码
Rate Limiting
限流规范
http
HTTP/1.1 200 OK
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1631234567Recommended limits:
- Public APIs: 100-1000 requests/hour
- Authenticated APIs: 1000-10000 requests/hour
- Webhooks: 10-100 requests/minute
http
HTTP/1.1 200 OK
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1631234567推荐限流阈值:
- 公共API: 每小时100-1000次请求
- 已认证API: 每小时1000-10000次请求
- Webhooks: 每分钟10-100次请求
Documentation Requirements
文档要求
- All endpoints documented
- Request/response examples
- Authentication requirements
- Error response formats
- Rate limits
- SDK examples (if available)
- 覆盖所有端点说明
- 提供请求/响应示例
- 标注认证要求
- 说明错误响应格式
- 标注限流规则
- 提供SDK示例(如有)
Scripts
配套脚本
Generate API scaffold:
bash
python scripts/generate_api.py <resource-name>Validate API design:
bash
python scripts/validate_api.py openapi.yaml生成API脚手架:
bash
python scripts/generate_api.py <resource-name>验证API设计合规性:
bash
python scripts/validate_api.py openapi.yamlReferences
参考资料
- - REST design patterns
references/rest-patterns.md - - GraphQL design patterns
references/graphql-patterns.md - REST API Tutorial
- GraphQL Best Practices
- - REST 设计模式
references/rest-patterns.md - - GraphQL 设计模式
references/graphql-patterns.md - REST API 教程
- GraphQL 最佳实践