5.0 KiB
5.0 KiB
前端 API 定义规范(REST 风格)
版本:v1.0
日期:2025-07-01
风格:RESTful
适用范围:Vue3 / React / 模块化 JS 项目
目标:提升接口命名一致性,增强可维护性与可读性
🌐 RESTful 命名规范
REST(Representational State Transfer)强调以资源为中心的接口设计,以下为规范核心:
✅ 基本动词与 HTTP 方法对应
动作 | HTTP 方法 | 路径示例 | 命名示例(函数) |
---|---|---|---|
获取列表 | GET | /users |
fetchUserList |
获取详情 | GET | /users/:id |
getUserById |
创建 | POST | /users |
createUser |
修改 | PUT/PATCH | /users/:id |
updateUser |
删除 | DELETE | /users/:id |
deleteUserById |
导出 | GET | /users/export |
exportUserExcel |
上传 | POST | /files/upload |
uploadFile |
📁 文件组织结构
src/
├── apis/
│ ├── landResourceManagement/ # 土地资源管理
│ │ ├── plantingPlan/ # 种植规划
│ │ │ ├── index.js
│ │ ├── operationRecord/ # 作业记录
│ │ │ ├── index.js
│ │ ├── landIllegal/ # 土地违法处理
│ │ │ ├── index.js
│ │ ├── landManagement/ # 土地管理
│ │ │ ├── index.js
│ │ ├── landInspection/ # 土地巡查
│ │ │ ├── index.js
│ │ ├── gridManagement/ # 网格管理
│ │ │ ├── index.js
│ │ ├── gridMemberManagement/ # 网格员管理
│ │ │ ├── index.js
│ │ ├── basicInfoMaintenance/ # 基础信息维护
│ │ │ ├── index.js
│ │ ├── cropsManagement/ # 种植作物
│ │ │ ├── index.js
│ │ ├── index.js # 土地资源管理模块统一入口
│ ├── productionEntityManagement/ # 生产经营主体管理
│ │ ├── index.js
│ ├── inputManagement/ # 投入品管理
│ │ ├── index.js
│ ├── productTraceability/ # 农产品溯源
│ │ ├── index.js
│ ├── index.js # 项目统一入口文件
├── utils/
│ ├── axios.js # 封装的请求工具
🧱 函数命名规范
接口定义应以 动词+资源名 格式命名函数(驼峰式 camelCase):
// 用户模块 API 示例
import request from '@/utils/request';
export function fetchUserList(params) {
return request('/api/users', { method: 'GET', params });
}
export function getUserById(id) {
return request(`/api/users/${id}`, { method: 'GET' });
}
export function createUser(data) {
return request('/api/users', { method: 'POST', data });
}
export function updateUser(id, data) {
return request(`/api/users/${id}`, { method: 'PUT', data });
}
export function deleteUserById(id) {
return request(`/api/users/${id}`, { method: 'DELETE' });
}
🧠 组件方法命名建议
组件内部方法(UI逻辑处理)请统一以 handle
前缀区分,避免与 API 冲突:
const handleAddUser = () => { ... };
const handleEditUser = (row) => { ... };
const handleDeleteUser = (id) => { ... };
const handleExportExcel = () => { ... };
🚫 命名反例
错误命名 | 问题说明 | 推荐命名 |
---|---|---|
listUser |
动词语义模糊 | fetchUserList |
editUserById |
与 REST 风格不符 | updateUser |
addOrEditUser |
接口职责不清晰 | createUser 或 updateUser |
removeUser |
与 HTTP 方法不一致 | deleteUserById |
🧾 附录:接口语义对照表
类型 | HTTP 方法 | REST URI 示例 | 函数命名示例 |
---|---|---|---|
查询列表 | GET | /entities |
fetchEntityList |
查询详情 | GET | /entities/:id |
getEntityById |
新增 | POST | /entities |
createEntity |
修改 | PUT | /entities/:id |
updateEntity |
删除 | DELETE | /entities/:id |
deleteEntityById |
导出 | GET | /entities/export |
exportEntityExcel |