前端 API 设计最佳实践:让你的 API 更优雅
毒舌时刻
API 设计?听起来就像是后端工程师的事情,关前端什么事?你以为前端只需要调用 API 就可以了?别天真了!如果 API 设计得不好,前端开发会变得非常痛苦。
你以为随便设计个 API 就能用?别做梦了!我见过太多糟糕的 API 设计,比如返回的数据结构不一致,错误处理不规范,文档不完整,这些都会让前端开发者崩溃。
为什么你需要这个
- 提高开发效率:良好的 API 设计可以减少前端开发的工作量,提高开发效率。
- 减少错误:规范的 API 设计可以减少前端开发中的错误,提高代码的可靠性。
- 改善用户体验:合理的 API 设计可以提高应用的响应速度,改善用户体验。
- 便于维护:良好的 API 设计可以使代码更易于维护,减少后期的维护成本。
- 促进团队协作:规范的 API 设计可以促进前后端团队的协作,减少沟通成本。
反面教材
// 这是一个典型的糟糕 API 设计 // 1. 不一致的命名规范 // 获取用户列表 fetch('/api/getUsers') .then(response => response.json()) .then(data => console.log(data)); // 获取单个用户 fetch('/api/user/1') .then(response => response.json()) .then(data => console.log(data)); // 2. 不一致的返回格式 // 成功返回 // { "status": "success", "data": { "id": 1, "name": "John" } } // 失败返回 // { "error": "User not found" } // 3. 不规范的错误处理 fetch('/api/users') .then(response => { if (response.status === 200) { return response.json(); } else if (response.status === 404) { throw new Error('Not found'); } else if (response.status === 500) { throw new Error('Server error'); } else { throw new Error('Unknown error'); } }) .then(data => console.log(data)) .catch(error => console.error(error)); // 4. 缺少分页和过滤 fetch('/api/users') .then(response => response.json()) .then(data => { // 当用户数量很多时,会返回大量数据,影响性能 console.log(data); });
问题:
- 命名规范不一致,有的使用驼峰命名,有的使用下划线命名
- 返回格式不一致,成功和失败的返回格式不同
- 错误处理不规范,需要手动处理不同的状态码
- 缺少分页和过滤功能,返回大量数据时影响性能
- 缺少版本控制,后续 API 变更时会影响现有代码
正确的做法
RESTful API 设计
// 1. 一致的命名规范 // 获取用户列表 fetch('/api/v1/users') .then(response => response.json()) .then(data => console.log(data)); // 获取单个用户 fetch('/api/v1/users/1') .then(response => response.json()) .then(data => console.log(data)); // 创建用户 fetch('/api/v1/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'John', email: '[email protected]' }) }) .then(response => response.json()) .then(data => console.log(data)); // 更新用户 fetch('/api/v1/users/1', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'John Doe', email: '[email protected]' }) }) .then(response => response.json()) .then(data => console.log(data)); // 删除用户 fetch('/api/v1/users/1', { method: 'DELETE' }) .then(response => response.json()) .then(data => console.log(data));

