api-designer

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API 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 user
Avoid:
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 方法规范

MethodSafeIdempotentPurpose
GETRead resource
POSTCreate resource
PUTReplace resource
PATCHUpdate resource
DELETEDelete resource
方法安全幂等用途
GET读取资源
POST创建资源
PUT替换资源
PATCH更新资源
DELETE删除资源

3. Status Codes

3. 状态码规范

CodeMeaningUsage
200OKSuccessful GET, PATCH, DELETE
201CreatedSuccessful POST
204No ContentSuccessful DELETE with no body
400Bad RequestInvalid input
401UnauthorizedMissing or invalid auth
403ForbiddenAuthenticated but not authorized
404Not FoundResource doesn't exist
409ConflictResource already exists
422UnprocessableValid syntax but semantic errors
429Too Many RequestsRate limit exceeded
500Internal Server ErrorServer 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,name
http
GET /users?status=active&sort=-created_at,name

-created_at = descending

-created_at = 按创建时间倒序

name = ascending

name = 按名称正序

undefined
undefined

GraphQL 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/users
Header Versioning:
GET /users
Accept: application/vnd.myapi.v2+json
URL 版本控制(推荐):
/api/v1/users
/api/v2/users
请求头版本控制:
GET /users
Accept: application/vnd.myapi.v2+json

Versioning Guidelines

版本控制规范

  • Start with v1
  • Maintain backwards compatibility when possible
  • Deprecate old versions with notice
  • Document breaking changes
  • 初始版本从v1开始
  • 尽可能保持向后兼容
  • 废弃旧版本前提前发出通知
  • 记录所有破坏性变更

Authentication & Authorization

认证与授权

Authentication Methods

认证方式

  1. JWT Bearer Token
http
Authorization: Bearer <token>
  1. API Key
http
X-API-Key: <key>
  1. OAuth 2.0
http
Authorization: Bearer <access_token>
  1. JWT Bearer Token
http
Authorization: Bearer <token>
  1. API Key
http
X-API-Key: <key>
  1. 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: 1631234567
Recommended 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.yaml

References

参考资料