designing-apis

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Designing APIs

API设计

When to Load

适用场景

  • Trigger: Designing REST or GraphQL endpoints, API contracts, versioning, request/response formats
  • Skip: Internal-only code with no API surface
  • 触发场景:设计REST或GraphQL端点、API契约、版本控制、请求/响应格式
  • 跳过场景:无API对外暴露的内部专属代码

API Design Workflow

API设计工作流

Copy this checklist and track progress:
API Design Progress:
- [ ] Step 1: Define resources and relationships
- [ ] Step 2: Design endpoint structure
- [ ] Step 3: Define request/response formats
- [ ] Step 4: Plan error handling
- [ ] Step 5: Add authentication/authorization
- [ ] Step 6: Document with OpenAPI spec
- [ ] Step 7: Validate design against checklist
复制以下清单并跟踪进度:
API设计进度:
- [ ] 步骤1:定义资源及关联关系
- [ ] 步骤2:设计端点结构
- [ ] 步骤3:定义请求/响应格式
- [ ] 步骤4:规划错误处理
- [ ] 步骤5:添加认证/授权机制
- [ ] 步骤6:使用OpenAPI规范编写文档
- [ ] 步骤7:对照清单验证设计

REST API Design

REST API设计

URL Structure

URL结构

undefined
undefined

Resource-based URLs (nouns, not verbs)

基于资源的URL(使用名词,而非动词)

GET /users # List users GET /users/:id # Get user POST /users # Create user PUT /users/:id # Replace user PATCH /users/:id # Update user DELETE /users/:id # Delete user
GET /users # 列出用户 GET /users/:id # 获取单个用户 POST /users # 创建用户 PUT /users/:id # 替换用户信息 PATCH /users/:id # 更新用户部分信息 DELETE /users/:id # 删除用户

Nested resources

嵌套资源

GET /users/:id/orders # User's orders POST /users/:id/orders # Create order for user
GET /users/:id/orders # 获取用户的订单 POST /users/:id/orders # 为用户创建订单

Query parameters for filtering/pagination

用于筛选/分页的查询参数

GET /users?role=admin&status=active GET /users?page=2&limit=20&sort=-createdAt
undefined
GET /users?role=admin&status=active GET /users?page=2&limit=20&sort=-createdAt
undefined

HTTP Status Codes

HTTP状态码

CodeMeaningUse Case
200OKSuccessful GET, PUT, PATCH
201CreatedSuccessful POST
204No ContentSuccessful DELETE
400Bad RequestInvalid input
401UnauthorizedMissing/invalid auth
403ForbiddenValid auth, no permission
404Not FoundResource doesn't exist
409ConflictDuplicate, state conflict
422UnprocessableValidation failed
429Too Many RequestsRate limited
500Internal ErrorServer error
状态码含义适用场景
200请求成功成功的GET、PUT、PATCH请求
201已创建成功的POST请求
204无内容成功的DELETE请求
400错误请求输入参数无效
401未授权缺少/无效的认证信息
403禁止访问认证有效但无权限
404资源不存在请求的资源不存在
409冲突重复请求或状态冲突
422无法处理的请求验证失败
429请求过于频繁触发速率限制
500服务器内部错误服务器端发生错误

Response Formats

响应格式

Success Response:
json
{
  "data": {
    "id": "123",
    "type": "user",
    "attributes": {
      "name": "John Doe",
      "email": "john@example.com"
    }
  },
  "meta": {
    "requestId": "abc-123"
  }
}
List Response with Pagination:
json
{
  "data": [...],
  "meta": {
    "total": 100,
    "page": 1,
    "limit": 20,
    "totalPages": 5
  },
  "links": {
    "self": "/users?page=1",
    "next": "/users?page=2",
    "last": "/users?page=5"
  }
}
Error Response:
json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input data",
    "details": [
      {
        "field": "email",
        "message": "Must be a valid email address"
      }
    ]
  },
  "meta": {
    "requestId": "abc-123"
  }
}
成功响应:
json
{
  "data": {
    "id": "123",
    "type": "user",
    "attributes": {
      "name": "John Doe",
      "email": "john@example.com"
    }
  },
  "meta": {
    "requestId": "abc-123"
  }
}
带分页的列表响应:
json
{
  "data": [...],
  "meta": {
    "total": 100,
    "page": 1,
    "limit": 20,
    "totalPages": 5
  },
  "links": {
    "self": "/users?page=1",
    "next": "/users?page=2",
    "last": "/users?page=5"
  }
}
错误响应:
json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input data",
    "details": [
      {
        "field": "email",
        "message": "Must be a valid email address"
      }
    ]
  },
  "meta": {
    "requestId": "abc-123"
  }
}

API Versioning

API版本控制

URL Versioning (Recommended):
/api/v1/users
/api/v2/users
Header Versioning:
Accept: application/vnd.api+json; version=1
URL版本控制(推荐):
/api/v1/users
/api/v2/users
请求头版本控制:
Accept: application/vnd.api+json; version=1

Authentication Patterns

认证模式

JWT Bearer Token:
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
API Key:
X-API-Key: your-api-key
JWT Bearer令牌:
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
API密钥:
X-API-Key: your-api-key

Rate Limiting Headers

速率限制响应头

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1609459200
Retry-After: 60
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1609459200
Retry-After: 60

GraphQL Patterns

GraphQL模式

Schema Design:
graphql
type Query {
  user(id: ID!): User
  users(filter: UserFilter, pagination: Pagination): UserConnection!
}

type Mutation {
  createUser(input: CreateUserInput!): UserPayload!
  updateUser(id: ID!, input: UpdateUserInput!): UserPayload!
}

type User {
  id: ID!
  name: String!
  email: String!
  orders(first: Int, after: String): OrderConnection!
}

input CreateUserInput {
  name: String!
  email: String!
}

type UserPayload {
  user: User
  errors: [Error!]
}
Schema设计:
graphql
type Query {
  user(id: ID!): User
  users(filter: UserFilter, pagination: Pagination): UserConnection!
}

type Mutation {
  createUser(input: CreateUserInput!): UserPayload!
  updateUser(id: ID!, input: UpdateUserInput!): UserPayload!
}

type User {
  id: ID!
  name: String!
  email: String!
  orders(first: Int, after: String): OrderConnection!
}

input CreateUserInput {
  name: String!
  email: String!
}

type UserPayload {
  user: User
  errors: [Error!]
}

OpenAPI Specification Template

OpenAPI规范模板

See OPENAPI-TEMPLATE.md for the full OpenAPI 3.0 specification template.
完整的OpenAPI 3.0规范模板请查看OPENAPI-TEMPLATE.md

API Design Validation

API设计验证

After completing the design, validate against this checklist:
Validation Checklist:
- [ ] All endpoints use nouns, not verbs
- [ ] HTTP methods match operations correctly
- [ ] Consistent response format across endpoints
- [ ] Error responses include actionable details
- [ ] Pagination implemented for list endpoints
- [ ] Authentication defined for protected endpoints
- [ ] Rate limiting headers documented
- [ ] OpenAPI spec is complete and valid
If validation fails, return to the relevant design step and address the issues.
完成设计后,对照以下清单进行验证:
验证清单:
- [ ] 所有端点使用名词而非动词
- [ ] HTTP方法与操作类型匹配正确
- [ ] 所有端点的响应格式保持一致
- [ ] 错误响应包含可操作的详细信息
- [ ] 列表端点已实现分页
- [ ] 受保护的端点已定义认证机制
- [ ] 速率限制响应头已文档化
- [ ] OpenAPI规范完整且有效
如果验证不通过,请回到对应设计步骤解决问题。

Security Checklist

安全清单

  • HTTPS only
  • Authentication on all endpoints
  • Authorization checks
  • Input validation
  • Rate limiting
  • Request size limits
  • CORS properly configured
  • No sensitive data in URLs
  • Audit logging
  • 仅使用HTTPS
  • 所有端点均需认证
  • 已添加权限校验
  • 已实现输入验证
  • 已配置速率限制
  • 已设置请求大小限制
  • CORS配置正确
  • URL中不包含敏感数据
  • 已启用审计日志