前端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

TongWeb中通道的线程任务队列大小(queueSize)和TCP等待队列大小(acceptCount)参数的含义和关系

TongWeb中通道maxQueueSize和acceptCount参数的含义和区别 在 TongWeb中,maxQueueSize 和 acceptCount 是两个与请求处理队列相关的核心参数,它们共同作用于并发请求的接收和处理流程,但所处的层面和作用机制有显著区别。理解两者的差异和协作关系,对优化 TongWeb 高并发性能至关重要。 * 参数定义与作用 1. acceptCount(操作系统层面的连接队列) * 作用:控制操作系统内核维护的 TCP 连接队列(backlog 队列) 的最大长度。当 TongWeb 的工作线程全部忙碌时,新到来的 TCP 连接会先进入该队列等待,直到有线程空闲后再被处理。 * 本质:这是操作系统层面的队列,用于暂存 “已建立但未被 TongWeb 应用层处理” 的 TCP 连接。 * 默认值:TongWeb8企业版默认值为500;TongWeb7嵌入式版本默认值为100。 * 队列满时的行为:若队列已满,新的 TCP 连接会被操作系统直接拒绝,客户端会收到 “Connection

【工具】无需Token!WebAI2API将网页AI转为API使用

【工具】无需Token!WebAI2API将网页AI转为API使用

转载请注明出处:小锋学长生活大爆炸[xfxuezhagn.cn] 如果本文帮助到了你,欢迎[点赞、收藏、关注]哦~ 背景介绍         想用OpenClaw、想在自己工具里集成API,但Token太贵了?不过,各大商家不是都提供了免费的网页版吗?比如doubao、ChatGPT,网页版是不限量还免费的!         所以这次介绍的工具,就是将网页版的AI转成了兼容OpenAI协议的API。以前也有web2api、chat2apt,不过都不更新了。而这次的WebAI2API非常好用。 使用效果         亲测效果挺好,原理就是:对外提供API接口,接收到请求后默认人工操作去内置浏览器上发送内容,然后将结果再返回给接口。 还提供了一个后端管理系统,可以方便的查看系统状态、管理配置等等。 不只是文字,图片生成也是能实现的。 如果你部署在服务器上,还能远程查看屏幕。 目前支持的AI厂商列表: 网站名称文本生成图片生成视频生成LMArena✅✅🚫Gemini Enterprise Business✅✅✅Nano Banana F

前端已死?元编程时代:用AI Skills重构你的开发工作流

摘要:本文深入探讨了新兴的“AI Skills”概念,它远不止是简单的Prompt技巧,而是一种将最佳实践、团队规范和技术栈封装成可执行文件的结构化工程范式。文章将系统阐述AI Skills如何从前端开发的“辅助工具”升级为“核心生产力”,通过UI组件生成、API客户端编码、智能测试等具体场景,展示其对工作流的颠覆性重构。我们将深入其技术原理,提供可操作的实践路径,并展望在这一范式下,前端开发者如何从“代码劳工”转变为“规则制定者”和“智能工作流架构师”。 关键字:AI Skills、前端开发、工作流重构、低错误率、Prompt工程、元编程 引言:超越ChatGPT,迎接“可编程的智能体” 🚀 如果你还停留在用ChatGPT手动复制粘贴代码片段,偶尔还要为它生成的过时或错误代码“擦屁股”的阶段,那么你正在浪费AI 90%的潜力。前端开发的范式革命已然来临,其核心不再是“会不会用AI”,而是“如何系统化、

【详细精选】前端面试题(2026精选附详细解答)包含10w数据展示优化、前端核心

【详细精选】前端面试题(2026精选附详细答案)包含10w数据展示优化、前端核心 * 前端面试题详细解答 * 1. ES6新特性详解(重要10个) * 核心特性 * 其他重要特性 * 2. 什么是跨域 * 同源策略 * 跨域解决方案 * 1.CORS(跨域资源共享) * 2.JSONP * 3. 代理服务器 * 4. WebSocket * 5. Nginx反向代理 * 3. 监听数组变化 * Vue2的实现原理 * Vue3的实现原理 * 4. v-if vs v-show * 原理对比 * 差异对比表 * 源码分析 * 5. 网页加载优化 * 性能指标(Core Web Vitals) * 优化策略 * 1. 代码优化 * 2. 资源优化 * 3. 缓存策略