RESTful API Practice

Security Best Practices

1. Authentication and Authorization

// 使用 JWT Token 进行身份验证
GET /api/users/profile
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

// API 响应包含用户权限检查
{
  "success": true,
  "data": {
    "id": 123,
    "name": "张三",
    "role": "user"
  }
}

2. Input Validation

// 服务器端验证示例
POST /api/users
{
  "email": "test@example.com",
  "password": "123"  // 密码太短
}

// 验证失败响应
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "密码长度至少为8位"
  }
}

3. HTTPS and Data Encryption

  • ✅ https://api.example.com/users
  • ❌ http://api.example.com/users

Performance Optimization Practices

1. Data Pagination

// 避免一次返回大量数据
GET /api/users?page=1&limit=20

{
  "success": true,
  "data": [...], // 只返回20条记录
  "pagination": {
    "currentPage": 1,
    "totalPages": 50,
    "totalItems": 1000
  }
}

2. Field Filtering

// 只返回需要的字段
GET /api/users?fields=id,name,email

{
  "success": true,
  "data": [
    {
      "id": 1,
      "name": "张三",
      "email": "zhangsan@example.com"
      // 不返回其他不需要的字段
    }
  ]
}

3. Caching Strategies

// 使用缓存头
GET /api/users/123
Cache-Control: max-age=3600  // 缓存1小时

// 条件请求
GET /api/users/123
If-None-Match: "etag-value"

// 304 Not Modified (数据未变化)

Error Handling Best Practices

Unified Error Format

{
  "success": false,
  "error": {
    "code": "SPECIFIC_ERROR_CODE",    // 机器可读的错误码
    "message": "用户友好的错误信息",      // 人类可读的错误信息
    "details": {...},                // 详细错误信息(可选)
    "timestamp": "2024-01-15T10:00:00Z"
  }
}

Common Error Code Design

const ERROR_CODES = {
  // 4xx 客户端错误
  'VALIDATION_ERROR': 400,        // 数据验证失败
  'UNAUTHORIZED': 401,            // 未授权
  'FORBIDDEN': 403,              // 禁止访问
  'NOT_FOUND': 404,              // 资源不存在
  'METHOD_NOT_ALLOWED': 405,     // 方法不允许
  'CONFLICT': 409,               // 资源冲突
  
  // 5xx 服务器错误
  'INTERNAL_ERROR': 500,         // 内部服务器错误
  'SERVICE_UNAVAILABLE': 503     // 服务不可用
}

API Documentation

Use Standardized Documentation Formats

Recommended to use the OpenAPI (Swagger) specification:

# swagger.yaml 示例
openapi: 3.0.0
info:
  title: 用户管理 API
  version: 1.0.0
  description: 提供用户的增删改查功能

paths:
  /api/users:
    get:
      summary: 获取用户列表
      parameters:
        - name: page
          in: query
          description: 页码
          schema:
            type: integer
            default: 1
      responses:
        '200':
          description: 成功
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/User'

Versioning Strategies

URL Versioning (Recommended)

// 版本1
GET /api/v1/users

// 版本2(新增字段,保持向后兼容)
GET /api/v2/users
{
  "id": 1,
  "name": "张三",
  "email": "zhangsan@example.com",
  "avatar": "https://example.com/avatar.jpg"  // 新增字段
}

Compatibility Handling

// 保持向后兼容的策略
{
  "deprecationWarning": "该 API 版本将在2024年6月1日后停止支持,请升级到 v2",
  "data": {...}
}

Practice Exercises

Exercise 1: Library Management System API

Design a simple library management system with the following features:

Requirements Analysis

  • Manage book information (title, author, ISBN, price)
  • Manage book categories
  • Support CRUD operations for books
  • Support filtering books by category

API Design Exercise

Please design the following API endpoints::

// 你的任务:完善以下 API 设计

// 图书相关
GET    /api/books                    // 获取图书列表
GET    /api/books/{id}              // 获取特定图书
POST   /api/books                   // 创建新图书
PUT    /api/books/{id}              // 更新图书信息
DELETE /api/books/{id}              // 删除图书

// 分类相关
GET    /api/categories              // 获取分类列表
GET    /api/categories/{id}/books   // 获取分类下的图书

Example Data Structure:

{
  "id": 1,
  "title": "JavaScript 高级程序设计",
  "author": "Nicholas C. Zakas",
  "isbn": "9787115275790",
  "price": 99.00,
  "categoryId": 1,
  "category": {
    "id": 1,
    "name": "编程技术"
  },
  "publishedDate": "2012-03-01",
  "description": "深入理解JavaScript语言",
  "stock": 50
}

Exercise Tasks

  1. Design API Documentation: Write detailed request and response examples for each endpoint
  2. Error Handling: Design response formats for various error scenarios
  3. Data Validation: List validation rules for each field
  4. Test Cases: Write curl commands to test each API

Exercise 2: Todo List API

Create a todo management API:

Functional Requirements

  • Create, view, update, and delete todo items
  • Mark task completion status
  • Filter tasks by status
  • Support task priority

Data Model Design

{
  "id": 1,
  "title": "学习 RESTful API",
  "description": "完成 API 教程的学习",
  "status": "pending",  // pending, completed, cancelled
  "priority": "high",   // low, medium, high
  "dueDate": "2024-01-20",
  "createdAt": "2024-01-15T08:00:00Z",
  "updatedAt": "2024-01-15T08:00:00Z"
}

Challenge Tasks

  1. Batch Operations: Design an API for batch updating task statuses
  2. Search Functionality: Support searching by title and description
  3. Statistics: Return statistical data on task completion

Exercise 3: Social Media API

Design an API for a simplified social media platform:

Core Features

  • User registration and login
  • Post and view feeds
  • Follow other users
  • Like and comment

API Structure Design

// 用户相关
POST /api/auth/register     // 用户注册
POST /api/auth/login        // 用户登录
GET  /api/users/profile     // 获取个人资料

// 动态相关
GET  /api/posts            // 获取动态列表
POST /api/posts            // 发布新动态
GET  /api/posts/{id}       // 获取特定动态
DELETE /api/posts/{id}     // 删除动态

// 互动相关
POST /api/posts/{id}/like     // 点赞动态
POST /api/posts/{id}/comments // 添加评论
GET  /api/posts/{id}/comments // 获取评论列表

Advanced Feature Design

  1. Follow System: Follow relationships between users
  2. Notifications: Notification mechanism for new interactions
  3. Content Moderation: Filtering of sensitive content
Other Extensions