[项目名称] API 接口文档
API版本:v1.0.0
BaseURL:https://api.example.com/v1
最后更新:2025-01-20
维护人:[API团队]
文档说明
这是一个API接口文档模板,适用于RESTful API、GraphQL等接口文档的编写。 包含完整的接口定义、请求示例、响应格式等内容。
一、接口概览
1.1 基本信息
| 项目 | 说明 |
|---|---|
| 协议 | HTTPS |
| 请求格式 | JSON |
| 响应格式 | JSON |
| 字符编码 | UTF-8 |
| 认证方式 | JWT Bearer Token |
1.2 接口列表
| 分类 | 接口数量 | 认证要求 | 限流策略 |
|---|---|---|---|
| 用户管理 | 8个 | 必需 | 100次/分钟 |
| 订单管理 | 12个 | 必需 | 200次/分钟 |
| 商品管理 | 10个 | 部分必需 | 1000次/分钟 |
| 支付接口 | 6个 | 必需 | 50次/分钟 |
| 系统接口 | 4个 | 不需要 | 无限制 |
二、通用规范
2.1 请求格式
请求头(Headers):
1Content-Type: application/json2Authorization: Bearer {access_token}3X-Request-ID: {unique_request_id}4Accept-Language: zh-CN通用参数:
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
timestamp | long | 否 | 请求时间戳(毫秒) |
sign | string | 否 | 签名(部分接口需要) |
2.2 响应格式
成功响应:
1{2 "code": 200,3 "message": "Success",4 "data": {5 // 具体数据6 },7 "timestamp": 1706227200000,8 "requestId": "req_1234567890"9}错误响应:
1{2 "code": 400,3 "message": "参数错误",4 "error": {5 "field": "email",6 "reason": "邮箱格式不正确"7 },8 "timestamp": 1706227200000,9 "requestId": "req_1234567890"10}2.3 状态码
| 状态码 | 说明 | 常见原因 |
|---|---|---|
| 200 | OK - 请求成功 | 正常返回 |
| 201 | Created - 创建成功 | 资源创建成功 |
| 400 | Bad Request - 请求错误 | 参数格式错误 |
| 401 | Unauthorized - 未授权 | Token无效或过期 |
| 403 | Forbidden - 禁止访问 | 权限不足 |
| 404 | Not Found - 资源不存在 | 请求的资源不存在 |
| 429 | Too Many Requests - 请求过多 | 超过限流阈值 |
| 500 | Internal Server Error - 服务器错误 | 服务器内部异常 |
2.4 业务状态码
| Code | Message | 说明 |
|---|---|---|
1000 | 成功 | 请求处理成功 |
1001 | 参数错误 | 请求参数不正确 |
1002 | 认证失败 | Token无效或过期 |
1003 | 权限不足 | 无权限访问该资源 |
1004 | 资源不存在 | 请求的资源不存在 |
1005 | 操作失败 | 业务操作失败 |
1006 | 重复操作 | 资源已存在或重复操作 |
1007 | 限流限制 | 请求频率超过限制 |
三、认证授权
3.1 获取Token
接口地址:POST /auth/login
请求参数:
1{2 "username": "user@example.com",3 "password": "P@ssw0rd123",4 "grant_type": "password"5}响应示例:
1{2 "code": 200,3 "message": "登录成功",4 "data": {5 "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",6 "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",7 "token_type": "Bearer",8 "expires_in": 7200,9 "user": {10 "id": 12345,11 "username": "user@example.com",12 "nickname": "张三",13 "avatar": "https://cdn.example.com/avatar/12345.jpg"14 }15 }16}3.2 刷新Token
接口地址:POST /auth/refresh
请求参数:
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
refresh_token | string | 是 | 刷新令牌 |
响应示例:
1{2 "code": 200,3 "message": "Token刷新成功",4 "data": {5 "access_token": "新的访问令牌",6 "expires_in": 72007 }8}3.3 Token使用
在请求头中携带Token:
1GET /api/users/profile HTTP/1.12Host: api.example.com3Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...4Content-Type: application/json四、用户管理接口
4.1 用户注册
接口说明:用户通过邮箱注册新账号
请求方式:POST
接口地址:/users/register
是否需要认证:否
请求参数:
| 参数名 | 类型 | 必填 | 说明 | 示例 |
|---|---|---|---|---|
email | string | 是 | 邮箱地址 | user@example.com |
password | string | 是 | 密码(8-20位,包含字母和数字) | P@ssw0rd123 |
username | string | 是 | 用户名(3-20位) | zhangsan |
phone | string | 否 | 手机号 | 13800138000 |
captcha | string | 是 | 验证码 | 1234 |
请求示例:
- cURL
- JavaScript
- Python
- Java
1curl -X POST "https://api.example.com/v1/users/register" \2 -H "Content-Type: application/json" \3 -d '{4 "email": "user@example.com",5 "password": "P@ssw0rd123",6 "username": "zhangsan",7 "phone": "13800138000",8 "captcha": "1234"9 }'1const response = await fetch('https://api.example.com/v1/users/register', {2 method: 'POST',3 headers: {4 'Content-Type': 'application/json'5 },6 body: JSON.stringify({7 email: 'user@example.com',8 password: 'P@ssw0rd123',9 username: 'zhangsan',10 phone: '13800138000',11 captcha: '1234'12 })13});1415const data = await response.json();16console.log(data);1import requests23url = "https://api.example.com/v1/users/register"4payload = {5 "email": "user@example.com",6 "password": "P@ssw0rd123",7 "username": "zhangsan",8 "phone": "13800138000",9 "captcha": "1234"10}1112response = requests.post(url, json=payload)13print(response.json())1OkHttpClient client = new OkHttpClient();23String json = "{\"email\":\"user@example.com\"," +4 "\"password\":\"P@ssw0rd123\"," +5 "\"username\":\"zhangsan\"," +6 "\"phone\":\"13800138000\"," +7 "\"captcha\":\"1234\"}";89RequestBody body = RequestBody.create(10 json, MediaType.parse("application/json"));1112Request request = new Request.Builder()13 .url("https://api.example.com/v1/users/register")14 .post(body)15 .build();1617Response response = client.newCall(request).execute();18System.out.println(response.body().string());响应示例:
1{2 "code": 200,3 "message": "注册成功",4 "data": {5 "userId": 12345,6 "email": "user@example.com",7 "username": "zhangsan",8 "createdAt": "2025-01-20T10:30:00Z"9 }10}错误响应:
1{2 "code": 1001,3 "message": "参数错误",4 "error": {5 "field": "email",6 "reason": "邮箱已被注册"7 }8}4.2 获取用户信息
接口说明:获取当前登录用户的详细信息
请求方式:GET
接口地址:/users/profile
是否需要认证:是(需要Bearer Token)
请求参数:无
请求示例:
1curl -X GET "https://api.example.com/v1/users/profile" \2 -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."响应示例:
1{2 "code": 200,3 "message": "获取成功",4 "data": {5 "userId": 12345,6 "username": "zhangsan",7 "email": "user@example.com",8 "phone": "13800138000",9 "avatar": "https://cdn.example.com/avatar/12345.jpg",10 "nickname": "张三",11 "gender": "male",12 "birthday": "1990-01-01",13 "address": {14 "province": "北京市",15 "city": "北京市",16 "district": "朝阳区",17 "detail": "xxx街道xxx号"18 },19 "status": "active",20 "role": "user",21 "createdAt": "2024-01-01T00:00:00Z",22 "lastLoginAt": "2025-01-20T10:00:00Z"23 }24}4.3 更新用户信息
接口说明:更新当前登录用户的个人信息
请求方式:PUT
接口地址:/users/profile
是否需要认证:是(需要Bearer Token)
请求参数:
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
nickname | string | 否 | 昵称 |
avatar | string | 否 | 头像URL |
gender | string | 否 | 性别:male/female/other |
birthday | string | 否 | 生日(YYYY-MM-DD) |
address | object | 否 | 地址信息 |
请求示例:
1{2 "nickname": "张三丰",3 "avatar": "https://cdn.example.com/avatar/new.jpg",4 "gender": "male",5 "birthday": "1990-01-01",6 "address": {7 "province": "北京市",8 "city": "北京市",9 "district": "海淀区",10 "detail": "中关村大街1号"11 }12}响应示例:
1{2 "code": 200,3 "message": "更新成功",4 "data": {5 "userId": 12345,6 "nickname": "张三丰",7 "avatar": "https://cdn.example.com/avatar/new.jpg",8 "updatedAt": "2025-01-20T11:00:00Z"9 }10}五、订单管理接口
5.1 创建订单
接口说明:用户创建新订单
请求方式:POST
接口地址:/orders
是否需要认证:是(需要Bearer Token)
业务流程:
请求参数:
1{2 "items": [3 {4 "productId": 10001,5 "quantity": 2,6 "price": 99.997 },8 {9 "productId": 10002,10 "quantity": 1,11 "price": 199.9912 }13 ],14 "shippingAddress": {15 "province": "北京市",16 "city": "北京市",17 "district": "朝阳区",18 "detail": "xxx街道xxx号",19 "recipient": "张三",20 "phone": "13800138000"21 },22 "remark": "请尽快发货",23 "couponCode": "DISCOUNT2025"24}响应示例:
1{2 "code": 200,3 "message": "订单创建成功",4 "data": {5 "orderId": "ORD202501200001",6 "orderNo": "20250120000000001",7 "status": "pending_payment",8 "totalAmount": 399.97,9 "discountAmount": 40.00,10 "payableAmount": 359.97,11 "items": [12 {13 "productId": 10001,14 "productName": "商品A",15 "quantity": 2,16 "price": 99.99,17 "subtotal": 199.9818 },19 {20 "productId": 10002,21 "productName": "商品B",22 "quantity": 1,23 "price": 199.99,24 "subtotal": 199.9925 }26 ],27 "shippingAddress": {28 "province": "北京市",29 "city": "北京市",30 "district": "朝阳区",31 "detail": "xxx街道xxx号",32 "recipient": "张三",33 "phone": "13800138000"34 },35 "paymentInfo": {36 "paymentId": "PAY202501200001",37 "paymentUrl": "https://pay.example.com/pay/123456",38 "qrCode": "https://cdn.example.com/qr/123456.png",39 "expiresAt": "2025-01-20T12:00:00Z"40 },41 "createdAt": "2025-01-20T11:30:00Z"42 }43}5.2 查询订单列表
接口说明:查询当前用户的订单列表
请求方式:GET
接口地址:/orders
是否需要认证:是(需要Bearer Token)
请求参数:
| 参数名 | 类型 | 必填 | 说明 | 默认值 |
|---|---|---|---|---|
page | int | 否 | 页码(从1开始) | 1 |
pageSize | int | 否 | 每页数量(1-100) | 10 |
status | string | 否 | 订单状态筛选 | all |
keyword | string | 否 | 搜索关键词 | - |
startDate | string | 否 | 开始日期 | - |
endDate | string | 否 | 结束日期 | - |
订单状态值:
| 状态值 | 中文名称 | 说明 |
|---|---|---|
| pending_payment | 待支付 | 订单已创建,等待支付 |
| paid | 已支付 | 支付完成,等待发货 |
| shipped | 已发货 | 商品已发出,等待收货 |
| completed | 已完成 | 订单已完成 |
| cancelled | 已取消 | 订单已取消 |
| refunding | 退款中 | 正在处理退款 |
| refunded | 已退款 | 退款已完成 |
请求示例:
1curl -X GET "https://api.example.com/v1/orders?page=1&pageSize=10&status=paid" \2 -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."响应示例:
1{2 "code": 200,3 "message": "查询成功",4 "data": {5 "list": [6 {7 "orderId": "ORD202501200001",8 "orderNo": "20250120000000001",9 "status": "paid",10 "statusText": "已支付",11 "totalAmount": 359.97,12 "itemCount": 3,13 "createdAt": "2025-01-20T11:30:00Z",14 "paidAt": "2025-01-20T11:35:00Z"15 }16 ],17 "pagination": {18 "page": 1,19 "pageSize": 10,20 "total": 45,21 "totalPages": 522 }23 }24}六、分页查询规范
6.1 请求参数
所有列表查询接口统一使用以下分页参数:
| 参数名 | 类型 | 必填 | 说明 | 默认值 |
|---|---|---|---|---|
page | int | 否 | 页码(从1开始) | 1 |
pageSize | int | 否 | 每页数量 | 10 |
sortBy | string | 否 | 排序字段 | - |
sortOrder | string | 否 | 排序方向:asc/desc | desc |
6.2 响应格式
1{2 "code": 200,3 "message": "查询成功",4 "data": {5 "list": [],6 "pagination": {7 "page": 1,8 "pageSize": 10,9 "total": 100,10 "totalPages": 10,11 "hasNext": true,12 "hasPrev": false13 }14 }15}七、错误处理
7.1 错误响应格式
1{2 "code": 1001,3 "message": "参数错误",4 "error": {5 "field": "email",6 "reason": "邮箱格式不正确",7 "value": "invalid-email"8 },9 "timestamp": 1706227200000,10 "requestId": "req_1234567890",11 "path": "/users/register"12}7.2 常见错误码
| Code | Message | 解决方案 |
|---|---|---|
1001 | 参数错误 | 检查请求参数格式 |
1002 | Token无效 | 重新登录获取Token |
1003 | 权限不足 | 联系管理员分配权限 |
1004 | 资源不存在 | 检查资源ID是否正确 |
1005 | 操作失败 | 查看详细错误信息 |
1006 | 重复操作 | 避免重复提交 |
1007 | 请求限流 | 降低请求频率 |
八、限流说明
8.1 限流策略
| 接口类型 | 限流规则 | 超限后行为 |
|---|---|---|
| 登录注册 | 10次/分钟/IP | 返回429状态码,60秒后重试 |
| 查询接口 | 100次/分钟/用户 | 返回429状态码,1分钟后重试 |
| 修改接口 | 50次/分钟/用户 | 返回429状态码,1分钟后重试 |
| 支付接口 | 10次/分钟/用户 | 返回429状态码,5分钟后重试 |
8.2 限流响应
1{2 "code": 1007,3 "message": "请求过于频繁,请稍后重试",4 "error": {5 "retryAfter": 60,6 "limit": 100,7 "remaining": 0,8 "resetAt": "2025-01-20T12:00:00Z"9 }10}九、Webhook回调
9.1 支付回调
回调URL:由商户在系统中配置
回调方式:POST
回调参数:
1{2 "eventType": "payment.success",3 "orderId": "ORD202501200001",4 "paymentId": "PAY202501200001",5 "amount": 359.97,6 "paidAt": "2025-01-20T11:35:00Z",7 "sign": "8a7b9c6d5e4f3g2h1i0j..."8}验证签名:
1const crypto = require('crypto');23function verifySign(data, sign, secret) {4 const str = Object.keys(data)5 .sort()6 .map(key => `${key}=${data[key]}`)7 .join('&');8 9 const hash = crypto10 .createHmac('sha256', secret)11 .update(str)12 .digest('hex');13 14 return hash === sign;15}十、SDK示例
10.1 JavaScript SDK
1class ApiClient {2 constructor(baseURL, token) {3 this.baseURL = baseURL;4 this.token = token;5 }6 7 async request(method, path, data = null) {8 const url = `${this.baseURL}${path}`;9 const options = {10 method,11 headers: {12 'Content-Type': 'application/json',13 'Authorization': `Bearer ${this.token}`14 }15 };16 17 if (data) {18 options.body = JSON.stringify(data);19 }20 21 const response = await fetch(url, options);22 return await response.json();23 }24 25 // 用户相关26 async getProfile() {27 return this.request('GET', '/users/profile');28 }29 30 async updateProfile(data) {31 return this.request('PUT', '/users/profile', data);32 }33 34 // 订单相关35 async createOrder(data) {36 return this.request('POST', '/orders', data);37 }38 39 async getOrders(params) {40 const query = new URLSearchParams(params).toString();41 return this.request('GET', `/orders?${query}`);42 }43}4445// 使用示例46const client = new ApiClient('https://api.example.com/v1', 'your_token');4748// 获取用户信息49const profile = await client.getProfile();50console.log(profile);5152// 创建订单53const order = await client.createOrder({54 items: [55 { productId: 10001, quantity: 2, price: 99.99 }56 ]57});58console.log(order);十一、测试工具
11.1 Postman集合
我们提供了完整的Postman集合,包含所有API接口的示例请求。
导入步骤:
- 下载 API.postman_collection.json
- 在Postman中选择 Import
- 选择下载的文件导入
11.2 在线调试
访问我们的API在线调试平台:
🔗 https://api-debug.example.com
十二、常见问题
Q1: 如何获取API密钥?
A: 登录开发者平台,在"应用管理"中创建应用并获取密钥。
Q2: Token过期后如何处理?
A: 使用refresh_token调用刷新接口获取新的access_token。
Q3: 如何调试Webhook回调?
A: 可以使用 webhook.site 或 ngrok 进行本地调试。
十三、联系我们
- 技术文档:https://docs.example.com
- 开发者社区:https://community.example.com
- 技术支持邮箱:api-support@example.com
- 工单系统:https://support.example.com
附录
A. 完整接口列表
查看 接口索引 获取完整的接口列表。
B. 更新日志
v1.0.0 (2025-01-20)
- 初始版本发布
- 支持用户管理、订单管理等基础功能
v0.9.0 (2025-01-10)
- Beta版本测试
评论