RESTful API Practical Application

User Management API Design

Let's design a complete user management system API, which is the most common application scenario.

API Endpoint Design

// 用户相关操作
GET    /api/users           # 获取用户列表
GET    /api/users/{id}      # 获取特定用户
POST   /api/users           # 创建新用户
PUT    /api/users/{id}      # 更新用户信息
DELETE /api/users/{id}      # 删除用户

// 用户订单相关操作
GET    /api/users/{id}/orders     # 获取用户的订单列表
POST   /api/users/{id}/orders     # 为用户创建订单
GET    /api/orders/{orderId}      # 获取特定订单详情

Complete CRUD Operations

1. Create User (Create)

// 请求
POST /api/users
Content-Type: application/json

{
  "name": "王五",
  "email": "[email protected]",
  "phone": "13800000000",
  "address": {
    "city": "上海",
    "street": "南京路100号"
  }
}

// 成功响应(状态码:201 Created)
{
  "success": true,
  "data": {
    "id": 125,
    "name": "王五",
    "email": "[email protected]",
    "phone": "13800000000",
    "address": {
      "city": "上海", 
      "street": "南京路100号"
    },
    "createdAt": "2024-01-15T10:00:00Z",
    "updatedAt": "2024-01-15T10:00:00Z"
  },
  "message": "用户创建成功"
}

2. Read User (Read)

// 获取用户列表
GET /api/users?page=1&limit=5&sort=createdAt&order=desc

// 响应(状态码:200 OK)
{
  "success": true,
  "data": [
    {
      "id": 125,
      "name": "王五",
      "email": "[email protected]",
      "createdAt": "2024-01-15T10:00:00Z"
    },
    {
      "id": 124,
      "name": "李四",
      "email": "[email protected]", 
      "createdAt": "2024-01-15T09:00:00Z"
    }
  ],
  "pagination": {
    "currentPage": 1,
    "totalPages": 3,
    "totalItems": 15,
    "itemsPerPage": 5
  }
}

// 获取特定用户
GET /api/users/125

// 响应
{
  "success": true,
  "data": {
    "id": 125,
    "name": "王五",
    "email": "[email protected]",
    "phone": "13800000000",
    "address": {
      "city": "上海",
      "street": "南京路100号"
    },
    "createdAt": "2024-01-15T10:00:00Z",
    "updatedAt": "2024-01-15T10:00:00Z"
  }
}

3. Update User (Update)

// 请求
PUT /api/users/125
Content-Type: application/json

{
  "name": "王五",
  "email": "[email protected]",
  "phone": "13900000000",
  "address": {
    "city": "深圳",
    "street": "科技园路200号"
  }
}

// 响应(状态码:200 OK)
{
  "success": true,
  "data": {
    "id": 125,
    "name": "王五",
    "email": "[email protected]",
    "phone": "13900000000",
    "address": {
      "city": "深圳",
      "street": "科技园路200号"
    },
    "createdAt": "2024-01-15T10:00:00Z",
    "updatedAt": "2024-01-15T11:30:00Z"
  },
  "message": "用户信息更新成功"
}

4. Delete User (Delete)

// 请求
DELETE /api/users/125

// 响应(状态码:200 OK)
{
  "success": true,
  "message": "用户删除成功"
}

// 如果用户不存在(状态码:404 Not Found)
{
  "success": false,
  "error": {
    "code": "USER_NOT_FOUND", 
    "message": "用户不存在"
  }
}

Error Handling

Data Validation Error

// 请求(邮箱格式错误)
POST /api/users
{
  "name": "",
  "email": "invalid-email",
  "phone": "123"
}

// 响应(状态码:400 Bad Request)
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "数据验证失败",
    "details": [
      {
        "field": "name",
        "message": "姓名不能为空"
      },
      {
        "field": "email", 
        "message": "邮箱格式不正确"
      },
      {
        "field": "phone",
        "message": "手机号格式不正确"
      }
    ]
  }
}

Resource Not Found Error

// 请求
GET /api/users/999

// 响应(状态码:404 Not Found)
{
  "success": false,
  "error": {
    "code": "USER_NOT_FOUND",
    "message": "用户不存在"
  }
}

Using JavaScript to Call the API

Example

// Use fetch API to call RESTful API

// 1. Get user list
async function getUsers() {
  try {
    const response = await fetch('/api/users');
    const result = await response.json();
   
    if (result.success) {
      console.log('User list:', result.data);
    } else {
      console.error('Failed to fetch:', result.error.message);
    }
  } catch (error) {
    console.error('Network error:', error);
  }
}

// 2. Create new user
async function createUser(userData) {
  try {
    const response = await fetch('/api/users', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(userData)
    });
   
    const result = await response.json();
   
    if (result.success) {
      console.log('User created successfully:', result.data);
    } else {
      console.error('Creation failed:', result.error.message);
    }
  } catch (error) {
    console.error('Network error:', error);
  }
}

// 3. Update user information
async function updateUser(userId, userData) {
  try {
    const response = await fetch(`/api/users/${userId}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(userData)
    });
   
    const result = await response.json();
   
    if (result.success) {
      console.log('User updated successfully:', result.data);
    } else {
      console.error('Update failed:', result.error.message);
    }
  } catch (error) {
    console.error('Network error:', error);
  }
}

// 4. Delete user
async function deleteUser(userId) {
  try {
    const response = await fetch(`/api/users/${userId}`, {
      method: 'DELETE'
    });
   
    const result = await response.json();
   
    if (result.success) {
      console.log('User deleted successfully');
    } else {
      console.error('Deletion failed:', result.error.message);
    }
  } catch (error) {
    console.error('Network error:', error);
  }
}
Other Extensions