Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

RESTful API Practice

RESTful API Practice

Security best practices

1. Authentication and authorization

// 使用 JWT Token 进行身份验证

GET /api/users/profile

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...



// API response includes user permission check

{

  "success": true,

  "data": {

    "id": 123,

    "name": "张三",

    "role": "user"

  }

}

2. Input validation

// 服务器端验证示例

POST /api/users

{

  "email": "test@example.com",

  "password": "123"  // 密码太短

}



// Validation failed response

{

  "success": false,

  "error": {

    "code": "VALIDATION_ERROR",

    "message": "密码长度至少为8位"

  }

}

3. HTTPS and data encryption


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"

      // Do not return other unnecessary fields

    }

  ]

}

3. Caching strategy

// 使用缓存头

GET /api/users/123

Cache-Control: max-age=3600  // 缓存1小时



// Conditional request

GET /api/users/123

If-None-Match: "etag-value"



// 304 Not Modified (Data unchanged)


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 Client error

  'VALIDATION_ERROR': 400,        // 数据验证失败

  'UNAUTHORIZED': 401,            // 未授权

  'FORBIDDEN': 403,              // 禁止访问

  'NOT_FOUND': 404,              // 资源不存在

  'METHOD_NOT_ALLOWED': 405,     // 方法不允许

  'CONFLICT': 409,               // 资源冲突

  

  // 5xx server error

  'INTERNAL_ERROR': 500,         // 内部服务器错误

  'SERVICE_UNAVAILABLE': 503     // 服务不可用

}


API documentation

Use a standardized documentation format

It is 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 strategy

URL versioning (recommended)

// 版本1

GET /api/v1/users



// Version 2 (added fields, maintaining backward compatibility)

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": {...}

}

Practical Exercise

Exercise 1: Library management system API

Design a simple library management system with the following features:

Requirements analysis

API design exercise

Please design the following API endpoints:

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



// Book related

GET    /api/books                    // 获取图书列表

GET    /api/books/{id}              // 获取特定图书

POST   /api/books                   // 创建新图书

PUT    /api/books/{id}              // 更新图书信息

DELETE /api/books/{id}              // 删除图书



// Classification related

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 the API documentationWrite detailed request and response examples for each endpoint
  2. Error handlingDesign response formats for various error situations
  3. Data validationList the validation rules for each field
  4. Test casesWrite curl commands to test each API

Exercise 2: Todo API

Create a todo management API:

Functional requirements

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 OperationsDesign an API to batch update task status
  2. Search functionalitySupport searching by title and description
  3. StatisticsReturn statistics on task completion

Exercise 3: Social media API

Design an API for a simplified social media platform:

Core Features

API structure design



// User related

POST /api/auth/register     // 用户注册

POST /api/auth/login        // 用户登录

GET  /api/users/profile     // 获取个人资料



// Dynamic related

GET  /api/posts            // 获取动态列表

POST /api/posts            // 发布新动态

GET  /api/posts/{id}       // 获取特定动态

DELETE /api/posts/{id}     // 删除动态



// Interaction related

POST /api/posts/{id}/like     // 点赞动态

POST /api/posts/{id}/comments // 添加评论

GET  /api/posts/{id}/comments // 获取评论列表

Advanced feature design

  1. Follow systemThe follow relationships between users
  2. Message pushNotification mechanism for new interactions
  3. Content moderationFiltering of sensitive content