前端 API 设计最佳实践
引言
API 设计通常被视为后端工程师的职责,但前端开发者同样需要关注其质量。如果 API 设计不当,将导致前端开发效率低下且维护困难。
为什么前端需要关注 API 设计
- 提高开发效率:良好的 API 设计可以减少前端开发的工作量。
- 减少错误:规范的 API 设计可以提高代码的可靠性。
- 改善用户体验:合理的 API 设计可以提高应用的响应速度。
- 便于维护:良好的 API 设计可以降低后期的维护成本。
- 促进团队协作:规范的 API 设计可以减少前后端沟通成本。
反面教材
// 1. 不一致的命名规范
fetch('/api/getUsers')
.then(response => response.json())
.then(data => console.log(data));
// 2. 不一致的返回格式
// 成功返回 { "status": "success", "data": {...} }
// 失败返回 { "error": "User not found" }
// 3. 不规范的错误处理
fetch('/api/users')
.then(response => {
if (response.status === 200) return response.json();
throw new Error('Server error');
})
.catch(error => console.error(error));
// 4. 缺少分页和过滤
fetch('/api/users').then(...);

