前端API设计最佳实践:让你的API更优雅

前端API设计最佳实践:让你的API更优雅

毒舌时刻

API设计?听起来就像是后端工程师的事情,关前端什么事?你以为前端只需要调用API就可以了?别天真了!如果API设计得不好,前端开发会变得非常痛苦。

你以为随便设计个API就能用?别做梦了!我见过太多糟糕的API设计,比如返回的数据结构不一致,错误处理不规范,文档不完整,这些都会让前端开发者崩溃。

为什么你需要这个

  1. 提高开发效率:良好的API设计可以减少前端开发的工作量,提高开发效率。
  2. 减少错误:规范的API设计可以减少前端开发中的错误,提高代码的可靠性。
  3. 改善用户体验:合理的API设计可以提高应用的响应速度,改善用户体验。
  4. 便于维护:良好的API设计可以使代码更易于维护,减少后期的维护成本。
  5. 促进团队协作:规范的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)); 

一致的返回格式

// 成功返回 // { // "success": true, // "data": { "id": 1, "name": "John" }, // "message": "User retrieved successfully" // } // 失败返回 // { // "success": false, // "error": { "code": 404, "message": "User not found" } // } // 统一的错误处理 async function fetchApi(url, options = {}) { try { const response = await fetch(url, options); const data = await response.json(); if (!data.success) { throw new Error(data.error?.message || 'Unknown error'); } return data.data; } catch (error) { console.error('API Error:', error); throw error; } } // 使用统一的错误处理 fetchApi('/api/v1/users') .then(data => console.log(data)) .catch(error => console.error(error)); 

分页和过滤

// 分页 fetch('/api/v1/users?page=1&limit=10') .then(response => response.json()) .then(data => console.log(data)); // 过滤 fetch('/api/v1/users?name=John&email=example.com') .then(response => response.json()) .then(data => console.log(data)); // 排序 fetch('/api/v1/users?sort=name&order=asc') .then(response => response.json()) .then(data => console.log(data)); 

API版本控制

// 使用URL路径进行版本控制 fetch('/api/v1/users') .then(response => response.json()) .then(data => console.log(data)); // 或使用请求头进行版本控制 fetch('/api/users', { headers: { 'Accept': 'application/vnd.example.v1+json' } }) .then(response => response.json()) .then(data => console.log(data)); 

API客户端封装

// api.js - 封装API客户端 class ApiClient { constructor(baseUrl) { this.baseUrl = baseUrl; } async request(endpoint, options = {}) { const url = `${this.baseUrl}${endpoint}`; const defaultOptions = { headers: { 'Content-Type': 'application/json' } }; const mergedOptions = { ...defaultOptions, ...options, headers: { ...defaultOptions.headers, ...options.headers } }; try { const response = await fetch(url, mergedOptions); const data = await response.json(); if (!data.success) { throw new Error(data.error?.message || 'Unknown error'); } return data.data; } catch (error) { console.error('API Error:', error); throw error; } } // 用户相关API getUsers(params = {}) { const queryString = new URLSearchParams(params).toString(); return this.request(`/users${queryString ? `?${queryString}` : ''}`); } getUser(id) { return this.request(`/users/${id}`); } createUser(user) { return this.request('/users', { method: 'POST', body: JSON.stringify(user) }); } updateUser(id, user) { return this.request(`/users/${id}`, { method: 'PUT', body: JSON.stringify(user) }); } deleteUser(id) { return this.request(`/users/${id}`, { method: 'DELETE' }); } } // 使用API客户端 const api = new ApiClient('https://api.example.com/v1'); // 获取用户列表 api.getUsers({ page: 1, limit: 10 }) .then(users => console.log(users)) .catch(error => console.error(error)); // 创建用户 api.createUser({ name: 'John', email: '[email protected]' }) .then(user => console.log(user)) .catch(error => console.error(error)); 

毒舌点评

API设计确实很重要,但我见过太多前端开发者把API设计的责任完全推给后端,自己只负责调用。你以为后端会自动设计出好的API?别做梦了!后端开发者可能不了解前端的需求,设计出来的API可能并不适合前端使用。

想象一下,当后端设计了一个返回格式不一致的API,前端需要写大量的代码来处理不同的返回格式,这会大大增加前端的开发工作量。

还有那些没有分页和过滤功能的API,当数据量很大时,前端会收到大量数据,导致应用变得很慢。

所以,前端开发者应该积极参与API设计,与后端开发者沟通,确保API设计符合前端的需求。

当然,API设计也不是越复杂越好。过于复杂的API设计会增加后端的开发成本,也会增加前端的学习成本。

最后,记住一句话:API设计的目的是为了方便使用,而不是为了炫技。如果你的API设计让使用者感到困惑,那你就失败了。

Read more

Claude Code免费使用教程,前端必看!

Claude Code免费使用教程,前端必看!

目前claude有两种使用方式,一种是官方购买渠道(太贵了,用不起,扎心。。。),还一种就是通过api方式,就是下面我讲的通过any-router提供的api调通就行~相当于中转站,主要是免费啊,谁能说不香! 1.注册LinuxDo账户 目前AnyRouter取消了github登录方式,只能通过LinuxDo账户登录,或者edu的邮箱登录,这里选择使用LinuxDo登录。 linux do官方网址:https://linux.do/   linux do邀请码:2E917F23-D9BF-44FE-BCBD-AE6AB3B1FC17 提示:如果Linuxdo邀请码失效,注册页面填写邀请码的那个输入框下面有邀请码链接,如图: 申请理由稍微写写,别全打逗号啥的,认真写下很快就过了。   2.any Router登录使用 上面linux do账号注册完毕就可以,登录any router了 any router网址:https://anyrouter.top/register?aff=iVs0    (貌似目前需要挂绿色软件才能登录上去) 一定要复制上面的网址(别删

前端组件库:别再重复造轮子了

前端组件库:别再重复造轮子了 毒舌时刻 这组件写得跟拼凑似的,一点都不统一。 各位前端同行,咱们今天聊聊前端组件库。别告诉我你还在手动编写所有组件,那感觉就像在没有工具的情况下盖房子——能盖,但效率低得可怜。 为什么你需要组件库 最近看到一个项目,每个组件都要手动编写,样式不统一,维护困难。我就想问:你是在做组件还是在做重复劳动? 反面教材 // 反面教材:手动编写组件 // Button.jsx import React from 'react'; function Button({ children, onClick }) { return ( <button onClick={onClick} style={{ padding: '10px 20px', backgroundColor: '#007bff', color: '

前端人别卷网页了!7天用Electron搞定桌面应用,工资翻倍不是梦

前端人别卷网页了!7天用Electron搞定桌面应用,工资翻倍不是梦

前端人别卷网页了!7天用Electron搞定桌面应用,工资翻倍不是梦 * 前端人别卷网页了!7天用Electron搞定桌面应用,工资翻倍不是梦 * 瞎扯淡的开场白:为什么你的简历还缺个"桌面端"项目 * 扒一扒Electron这货的底裤 * 套壳浏览器?这么说对也不对 * 除了Electron,这几个备胎也得认识 * 为啥大厂都爱用Electron? * 手把手教你把网页"塞"进桌面图标里 * 脚手架一把梭,别傻傻敲命令 * main.js里的那些破事儿 * preload脚本:别把它当摆设 * 这框架虽好,但这几个坑踩进去就拔不出来 * 打包体积:塞了整个Chrome进去? * 内存占用:低配电脑杀手 * 自动更新:配置起来想砸键盘 * 安全性:别让应用变成筛子 * 实战环节:做个能摸鱼的本地记事本 * 程序崩了别只会重启,这几招能让你少掉几根头发 * 主进程挂了怎么查? * 渲染进程白屏了? * 内存泄漏排查

Java Web web新能源充电系统系统源码-SpringBoot2+Vue3+MyBatis-Plus+MySQL8.0【含文档】

Java Web web新能源充电系统系统源码-SpringBoot2+Vue3+MyBatis-Plus+MySQL8.0【含文档】

💡实话实说: C有自己的项目库存,不需要找别人拿货再加价。 摘要 随着全球能源结构的转型和新能源汽车的普及,充电基础设施的建设成为推动行业发展的关键环节。传统充电系统存在效率低、管理不便、用户体验差等问题,亟需通过智能化手段进行优化。新能源充电系统通过整合物联网、云计算等技术,实现充电桩的远程监控、智能调度和用户便捷操作,为新能源汽车用户提供高效、安全的充电服务。该系统不仅提升了充电设施的利用率,还通过数据分析优化了能源分配,降低了运营成本。关键词:新能源充电系统、充电桩、物联网、云计算、智能化。 本系统基于SpringBoot2框架构建后端服务,采用Vue3作为前端开发框架,结合MyBatis-Plus实现数据持久化操作,MySQL8.0作为数据库存储数据。系统功能包括用户管理、充电桩管理、订单管理、支付管理和数据分析模块。用户可通过移动端或Web端实时查询充电桩状态、预约充电、在线支付,管理员则能监控设备运行状态、统计运营数据并生成报表。系统通过RESTful API实现前后端分离,确保高内聚低耦合的架构设计,同时利用Redis缓存提升响应速度。关键词:SpringBoo