api-design

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API Design

API设计

When to use this skill

何时使用此技能

  • Designing new REST APIs
  • Creating GraphQL schemas
  • Refactoring API endpoints
  • Documenting API specifications
  • API versioning strategies
  • Defining data models and relationships
  • 设计新的REST API
  • 创建GraphQL schema
  • 重构API端点
  • 编写API规范
  • API版本管理策略
  • 定义数据模型与实体关系

Instructions

操作指南

Step 1: Define API requirements

步骤1:定义API需求

  • Identify resources and entities
  • Define relationships between entities
  • Specify operations (CRUD, custom actions)
  • Plan authentication/authorization
  • Consider pagination, filtering, sorting
  • 识别资源与实体
  • 定义实体间的关系
  • 指定操作类型(CRUD、自定义操作)
  • 规划认证/授权机制
  • 考虑分页、过滤、排序功能

Step 2: Design REST API

步骤2:设计REST API

Resource naming:
  • Use nouns, not verbs:
    /users
    not
    /getUsers
  • Use plural names:
    /users/{id}
  • Nest resources logically:
    /users/{id}/posts
  • Keep URLs short and intuitive
HTTP methods:
  • GET
    : Retrieve resources (idempotent)
  • POST
    : Create new resources
  • PUT
    : Replace entire resource
  • PATCH
    : Partial update
  • DELETE
    : Remove resources (idempotent)
Response codes:
  • 200 OK
    : Success with response body
  • 201 Created
    : Resource created successfully
  • 204 No Content
    : Success with no response body
  • 400 Bad Request
    : Invalid input
  • 401 Unauthorized
    : Authentication required
  • 403 Forbidden
    : No permission
  • 404 Not Found
    : Resource doesn't exist
  • 409 Conflict
    : Resource conflict
  • 422 Unprocessable Entity
    : Validation failed
  • 500 Internal Server Error
    : Server error
Example REST endpoint:
GET    /api/v1/users           # List users
GET    /api/v1/users/{id}      # Get user
POST   /api/v1/users           # Create user
PUT    /api/v1/users/{id}      # Update user
PATCH  /api/v1/users/{id}      # Partial update
DELETE /api/v1/users/{id}      # Delete user
资源命名规则:
  • 使用名词而非动词:
    /users
    而非
    /getUsers
  • 使用复数形式:
    /users/{id}
  • 合理嵌套资源:
    /users/{id}/posts
  • 保持URL简洁直观
HTTP方法使用:
  • GET
    : 获取资源(幂等操作)
  • POST
    : 创建新资源
  • PUT
    : 替换整个资源
  • PATCH
    : 部分更新资源
  • DELETE
    : 删除资源(幂等操作)
响应状态码:
  • 200 OK
    : 请求成功并返回响应体
  • 201 Created
    : 资源创建成功
  • 204 No Content
    : 请求成功但无响应体
  • 400 Bad Request
    : 输入参数无效
  • 401 Unauthorized
    : 需要身份认证
  • 403 Forbidden
    : 无访问权限
  • 404 Not Found
    : 资源不存在
  • 409 Conflict
    : 资源冲突
  • 422 Unprocessable Entity
    : 验证失败
  • 500 Internal Server Error
    : 服务器内部错误
REST端点示例:
GET    /api/v1/users           # 列出用户
GET    /api/v1/users/{id}      # 获取单个用户
POST   /api/v1/users           # 创建用户
PUT    /api/v1/users/{id}      # 更新用户
PATCH  /api/v1/users/{id}      # 部分更新用户
DELETE /api/v1/users/{id}      # 删除用户

Step 3: Request/Response format

步骤3:请求/响应格式

Request example:
json
POST /api/v1/users
Content-Type: application/json

{
  "name": "John Doe",
  "email": "john@example.com",
  "role": "admin"
}
Response example:
json
HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/v1/users/123

{
  "id": 123,
  "name": "John Doe",
  "email": "john@example.com",
  "role": "admin",
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-15T10:30:00Z"
}
请求示例:
json
POST /api/v1/users
Content-Type: application/json

{
  "name": "John Doe",
  "email": "john@example.com",
  "role": "admin"
}
响应示例:
json
HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/v1/users/123

{
  "id": 123,
  "name": "John Doe",
  "email": "john@example.com",
  "role": "admin",
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-15T10:30:00Z"
}

Step 4: Error handling

步骤4:错误处理

Error response format:
json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input provided",
    "details": [
      {
        "field": "email",
        "message": "Invalid email format"
      }
    ]
  }
}
错误响应格式:
json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid input provided",
    "details": [
      {
        "field": "email",
        "message": "Invalid email format"
      }
    ]
  }
}

Step 5: Pagination

步骤5:分页功能

Query parameters:
GET /api/v1/users?page=2&limit=20&sort=-created_at&filter=role:admin
Response with pagination:
json
{
  "data": [...],
  "pagination": {
    "page": 2,
    "limit": 20,
    "total": 100,
    "pages": 5
  },
  "links": {
    "self": "/api/v1/users?page=2&limit=20",
    "first": "/api/v1/users?page=1&limit=20",
    "prev": "/api/v1/users?page=1&limit=20",
    "next": "/api/v1/users?page=3&limit=20",
    "last": "/api/v1/users?page=5&limit=20"
  }
}
查询参数示例:
GET /api/v1/users?page=2&limit=20&sort=-created_at&filter=role:admin
带分页的响应示例:
json
{
  "data": [...],
  "pagination": {
    "page": 2,
    "limit": 20,
    "total": 100,
    "pages": 5
  },
  "links": {
    "self": "/api/v1/users?page=2&limit=20",
    "first": "/api/v1/users?page=1&limit=20",
    "prev": "/api/v1/users?page=1&limit=20",
    "next": "/api/v1/users?page=3&limit=20",
    "last": "/api/v1/users?page=5&limit=20"
  }
}

Step 6: Authentication

步骤6:认证机制

Options:
  • JWT (JSON Web Tokens)
  • OAuth 2.0
  • API Keys
  • Session-based
Example with JWT:
GET /api/v1/users
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
可选方案:
  • JWT (JSON Web Tokens)
  • OAuth 2.0
  • API密钥
  • 基于会话的认证
JWT示例:
GET /api/v1/users
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Step 7: Versioning

步骤7:版本管理

URL versioning (recommended):
/api/v1/users
/api/v2/users
Header versioning:
GET /api/users
Accept: application/vnd.api+json; version=1
URL版本管理(推荐):
/api/v1/users
/api/v2/users
请求头版本管理:
GET /api/users
Accept: application/vnd.api+json; version=1

Step 8: Documentation

步骤8:文档编写

Create OpenAPI 3.0 specification:
yaml
openapi: 3.0.0
info:
  title: User Management API
  version: 1.0.0
  description: API for managing users
servers:
  - url: https://api.example.com/v1
paths:
  /users:
    get:
      summary: List users
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/User'
    post:
      summary: Create user
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UserCreate'
      responses:
        '201':
          description: User created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
        email:
          type: string
          format: email
        created_at:
          type: string
          format: date-time
    UserCreate:
      type: object
      required:
        - name
        - email
      properties:
        name:
          type: string
        email:
          type: string
          format: email
创建OpenAPI 3.0规范:
yaml
openapi: 3.0.0
info:
  title: User Management API
  version: 1.0.0
  description: API for managing users
servers:
  - url: https://api.example.com/v1
paths:
  /users:
    get:
      summary: List users
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/User'
    post:
      summary: Create user
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UserCreate'
      responses:
        '201':
          description: User created
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
        name:
          type: string
        email:
          type: string
          format: email
        created_at:
          type: string
          format: date-time
    UserCreate:
      type: object
      required:
        - name
        - email
      properties:
        name:
          type: string
        email:
          type: string
          format: email

Best practices

最佳实践

  1. Consistency: Use consistent naming, structure, and patterns
  2. Versioning: Always version your APIs from the start
  3. Security: Implement authentication and authorization
  4. Validation: Validate all inputs on the server side
  5. Rate limiting: Protect against abuse
  6. Caching: Use ETags and Cache-Control headers
  7. CORS: Configure properly for web clients
  8. Documentation: Keep docs up-to-date with code
  9. Testing: Test all endpoints thoroughly
  10. Monitoring: Log requests and track performance
  1. 一致性:使用统一的命名、结构和模式
  2. 版本管理:从项目初期就为API添加版本管理
  3. 安全性:实现认证与授权机制
  4. 输入验证:在服务端验证所有输入内容
  5. 请求限流:防止API被滥用
  6. 缓存策略:使用ETag和Cache-Control请求头
  7. CORS配置:为Web客户端正确配置跨域资源共享
  8. 文档维护:保持文档与代码同步更新
  9. 测试覆盖:全面测试所有API端点
  10. 监控追踪:记录请求并跟踪性能指标

Common patterns

常见模式

Filtering:
GET /api/v1/users?role=admin&status=active
Sorting:
GET /api/v1/users?sort=-created_at,name
Field selection:
GET /api/v1/users?fields=id,name,email
Batch operations:
POST /api/v1/users/batch
{
  "operations": [
    {"action": "create", "data": {...}},
    {"action": "update", "id": 123, "data": {...}}
  ]
}
过滤功能:
GET /api/v1/users?role=admin&status=active
排序功能:
GET /api/v1/users?sort=-created_at,name
字段选择:
GET /api/v1/users?fields=id,name,email
批量操作:
POST /api/v1/users/batch
{
  "operations": [
    {"action": "create", "data": {...}},
    {"action": "update", "id": 123, "data": {...}}
  ]
}

GraphQL alternative

GraphQL替代方案

If REST doesn't fit, consider GraphQL:
graphql
type User {
  id: ID!
  name: String!
  email: String!
  posts: [Post!]!
  createdAt: DateTime!
}

type Query {
  users(page: Int, limit: Int): [User!]!
  user(id: ID!): User
}

type Mutation {
  createUser(input: CreateUserInput!): User!
  updateUser(id: ID!, input: UpdateUserInput!): User!
  deleteUser(id: ID!): Boolean!
}
如果REST不符合需求,可以考虑使用GraphQL:
graphql
type User {
  id: ID!
  name: String!
  email: String!
  posts: [Post!]!
  createdAt: DateTime!
}

type Query {
  users(page: Int, limit: Int): [User!]!
  user(id: ID!): User
}

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

References

参考资料

Examples

示例

Example 1: Basic usage

示例1:基础用法

<!-- Add example content here -->
<!-- 在此添加示例内容 -->

Example 2: Advanced usage

示例2:高级用法

<!-- Add advanced example content here -->
<!-- 在此添加高级示例内容 -->