RESTful API实际应用场景与开发实践
时间:2026-08-14 | 作者:风起客 | 阅读:0用户管理 API 设计
不妨就以最典型的场景为切入点:设计一套完整的用户管理系统 API。
API 端点设计
// 用户相关操作
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} # 获取特定订单详情
完整的 CRUD 操作
1. 创建用户(Create)
// 请求
POST /api/users
Content-Type: application/json
{
"name": "王五",
"email": "wangwu@example.com",
"phone": "13800000000",
"address": {
"city": "上海",
"street": "南京路100号"
}
}
// 成功响应(状态码:201 Created)
{
"success": true,
"data": {
"id": 125,
"name": "王五",
"email": "wangwu@example.com",
"phone": "13800000000",
"address": {
"city": "上海",
"street": "南京路100号"
},
"createdAt": "2024-01-15T10:00:00Z",
"updatedAt": "2024-01-15T10:00:00Z"
},
"message": "用户创建成功"
}2. 读取用户(Read)
// 获取用户列表
GET /api/userspage=1&limit=5&sort=createdAt&order=desc
// 响应(状态码:200 OK)
{
"success": true,
"data": [
{
"id": 125,
"name": "王五",
"email": "wangwu@example.com",
"createdAt": "2024-01-15T10:00:00Z"
},
{
"id": 124,
"name": "李四",
"email": "lisi@example.com",
"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": "wangwu@example.com",
"phone": "13800000000",
"address": {
"city": "上海",
"street": "南京路100号"
},
"createdAt": "2024-01-15T10:00:00Z",
"updatedAt": "2024-01-15T10:00:00Z"
}
}3. 更新用户(Update)
// 请求
PUT /api/users/125
Content-Type: application/json
{
"name": "王五",
"email": "wangwu.new@example.com",
"phone": "13900000000",
"address": {
"city": "深圳",
"street": "科技园路200号"
}
}
// 响应(状态码:200 OK)
{
"success": true,
"data": {
"id": 125,
"name": "王五",
"email": "wangwu.new@example.com",
"phone": "13900000000",
"address": {
"city": "深圳",
"street": "科技园路200号"
},
"createdAt": "2024-01-15T10:00:00Z",
"updatedAt": "2024-01-15T11:30:00Z"
},
"message": "用户信息更新成功"
}4. 删除用户(Delete)
// 请求
DELETE /api/users/125
// 响应(状态码:200 OK)
{
"success": true,
"message": "用户删除成功"
}
// 如果用户不存在(状态码:404 Not Found)
{
"success": false,
"error": {
"code": "USER_NOT_FOUND",
"message": "用户不存在"
}
}错误处理
数据验证错误
// 请求(邮箱格式错误)
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": "手机号格式不正确"
}
]
}
}资源不存在错误
// 请求
GET /api/users/999
// 响应(状态码:404 Not Found)
{
"success": false,
"error": {
"code": "USER_NOT_FOUND",
"message": "用户不存在"
}
}使用 Ja vaScript 调用 API
实例
// 使用 fetch API 调用 RESTful API
// 1. 获取用户列表
async function getUsers() {
try {
const response = await fetch('/api/users');
const result = await response.json();
if (result.success) {
console.log('用户列表:', result.data);
} else {
console.error('获取失败:', result.error.message);
}
} catch (error) {
console.error('网络错误:', error);
}
}
// 2. 创建新用户
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('用户创建成功:', result.data);
} else {
console.error('创建失败:', result.error.message);
}
} catch (error) {
console.error('网络错误:', error);
}
}
// 3. 更新用户信息
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('用户更新成功:', result.data);
} else {
console.error('更新失败:', result.error.message);
}
} catch (error) {
console.error('网络错误:', error);
}
}
// 4. 删除用户
async function deleteUser(userId) {
try {
const response = await fetch(`/api/users/${userId}`, {
method: 'DELETE'
});
const result = await response.json();
if (result.success) {
console.log('用户删除成功');
} else {
console.error('删除失败:', result.error.message);
}
} catch (error) {
console.error('网络错误:', error);
}
}
免责声明:文中图文均来自网络,如有侵权请联系删除,心愿游戏发布此文仅为传递信息,不代表心愿游戏认同其观点或证实其描述。
相关文章
更多-
- RESTful API请求与响应格式详解及设计规范
- 时间:2026-08-15
-
- RESTful API测试与调试方法及常见问题解析
- 时间:2026-08-14
-
- RESTful API 入门教程与接口设计实践
- 时间:2026-08-14
-
- RESTful API 进阶实践与设计优化指南
- 时间:2026-08-14
-
- RESTful URL设计规范与最佳实践指南
- 时间:2026-08-14
-
- RESTful API 测验题与接口开发基础指南
- 时间:2026-08-14
精选合集
更多大家都在玩
大家都在看
更多-
- 以下哪种食材被称为“地下苹果” 蚂蚁庄园今日答案9.18
- 时间:2026-09-17
-
- 蚂蚁庄园今天答题答案2026年9月18日
- 时间:2026-09-17
-
- 蚂蚁庄园答题今日答案2026年9月18日
- 时间:2026-09-17
-
- 蚂蚁庄园小课堂2026年9月18日最新题目答案
- 时间:2026-09-17
-
- 小鸡答题今天的答案是什么2026年9月18日
- 时间:2026-09-17
-
- 蚂蚁庄园每日答题答案2026年9月18日
- 时间:2026-09-17
-
- 蔬菜洗完掉色,说明是被染色了,是真的吗 蚂蚁庄园今日答案9月18日
- 时间:2026-09-17
-
- 满襟蜡绘花纹巧染就花纹当绣裳说的是哪种传统技艺 蚂蚁新村今日答案2026.9.17
- 时间:2026-09-17
