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

唤醒80年代记忆:基于百度地图的一次老式天气预报的WebGIS构建之旅

唤醒80年代记忆:基于百度地图的一次老式天气预报的WebGIS构建之旅

目录 一、省会城市信息构建 1、省会城市空间查询 2、Java后台查询 二、Java省会城市天气查询 1、与百度开放平台集成天气 2、响应对象属性介绍 3、省会天气实况展示 三、WebGIS应用构建 1、背景音乐集成 2、城市标记及天气展示 3、城市轮播 4、成果展示 四、总结 前言         在数字技术飞速发展的今天,我们常常沉浸于各种高科技带来的便捷与震撼之中,却容易忽视那些曾经陪伴我们成长、承载着时代记忆的旧事物。80年代的天气预报,便是这样一份珍贵的文化遗产。它以简洁而质朴的方式,传递着天气信息,也传递着那个时代的气息。那种对自然的敬畏、对信息的渴望,以及一家人共同分享的温馨氛围,都深深烙印在我们的记忆中。然而,随着时间的推移,天气预报的形式已经发生了翻天覆地的变化。高清的画面、精准的数据、个性化的推送……这些现代技术带来的便利固然令人欣喜,但也在一定程度上让我们失去了那份对天气预报本身的纯粹情感。于是,

【通过 Vue 实例劫持突破 Web 编辑器的粘贴限制】

【通过 Vue 实例劫持突破 Web 编辑器的粘贴限制】

逆向实战:通过 Vue 实例劫持突破 Web 编辑器的粘贴限制 * 第一种类型(含分析,可直接跳过至4.1查看方法) * 1. 现象与初探:被禁用的 Ctrl+V * 技术视角的初步审视 * 逆向的逻辑前提 * 2. 逆向分析:寻找逻辑的“命门” * 突破口:利用 I18N 国际化配置追踪 * 核心文件追踪:锁定 `answer-code-editor.js` * 代码逻辑解剖:拦截机制的实现 * 3. 攻克方案:Vue 实例的运行时劫持 * 第一步:获取 Vue 实例的“后门” * 第二步:函数劫持(Monkey Patch) * 第三步:状态机的一致性重构 * 第四步:唤醒底层编辑器 * 4. 最终脚本:

Flutter for OpenHarmony: Flutter 三方库 jaspr 为鸿蒙端开启极速渲染的现代 Web 开发新范式(Dart Web 框架首选)

Flutter for OpenHarmony: Flutter 三方库 jaspr 为鸿蒙端开启极速渲染的现代 Web 开发新范式(Dart Web 框架首选)

欢迎加入开源鸿蒙跨平台社区:https://openharmonycrossplatform.ZEEKLOG.net 前言 在进行 OpenHarmony 开发时,我们偶尔需要跳出原生的 HAP 容器,寻找更轻量、更适合在移动端 Web 加载的方案。虽然 Flutter Web 极其强大,但其生成的 Canvas/Wasm 产物体积巨大,在鸿蒙系统加载较慢。是否存在一种方案,既能使用 Dart 的声明式开发体验,又能产出纯正、轻量的 HTML/CSS/JS 节点? jaspr 就是这个问题的终极答案。它是一个模仿 Flutter 语法、但专注于渲染原生 Web DOM 的现代框架。通过 Jaspr,鸿蒙开发者可以利用熟悉的 Widget、Component 和生命周期,

Youtu-VL-4B-Instruct源码实战:基于Gradio自定义组件扩展WebUI的图片批处理功能

Youtu-VL-4B-Instruct源码实战:基于Gradio自定义组件扩展WebUI的图片批处理功能 1. 引言:从单张到批量,解放生产力的新思路 如果你用过Youtu-VL-4B-Instruct的WebUI,肯定体验过它的强大——上传一张图片,问几个问题,模型就能给出精准的回答。无论是识别图片里的文字,还是描述复杂的场景,这个40亿参数的多模态模型都表现得相当不错。 但不知道你有没有遇到过这样的场景:手头有几十张产品图片需要批量添加描述,或者有一堆文档截图需要统一提取文字。这时候,一张一张上传、等待、再上传,效率实在太低了。每次操作都要重复“上传-等待-复制结果”的流程,不仅耗时,还容易出错。 这就是我们今天要解决的问题。原生的WebUI界面虽然友好,但在批量处理方面存在明显短板。它就像一家只接受堂食的餐厅,味道很好,但没法做外卖。而我们需要的是能同时处理多份订单的中央厨房。 好消息是,Gradio框架给了我们足够的灵活性。通过深入源码,我们可以自己动手,为这个WebUI增加一个“图片批处理”功能。想象一下,一次性上传几十张图片,设置好统一的提问模板,然后去喝杯咖