跳到主要内容

[项目名称] API 接口文档

API版本:v1.0.0
BaseURLhttps://api.example.com/v1
最后更新:2025-01-20
维护人:[API团队]


文档说明

使用说明

这是一个API接口文档模板,适用于RESTful API、GraphQL等接口文档的编写。 包含完整的接口定义、请求示例、响应格式等内容。


一、接口概览

1.1 基本信息

项目说明
协议HTTPS
请求格式JSON
响应格式JSON
字符编码UTF-8
认证方式JWT Bearer Token

1.2 接口列表

API接口总览
分类接口数量认证要求限流策略
用户管理8个必需100次/分钟
订单管理12个必需200次/分钟
商品管理10个部分必需1000次/分钟
支付接口6个必需50次/分钟
系统接口4个不需要无限制

二、通用规范

2.1 请求格式

请求头(Headers)

http
1Content-Type: application/json
2Authorization: Bearer {access_token}
3X-Request-ID: {unique_request_id}
4Accept-Language: zh-CN

通用参数

参数名类型必填说明
timestamplong请求时间戳(毫秒)
signstring签名(部分接口需要)

2.2 响应格式

成功响应

json
1{
2 "code": 200,
3 "message": "Success",
4 "data": {
5 // 具体数据
6 },
7 "timestamp": 1706227200000,
8 "requestId": "req_1234567890"
9}

错误响应

json
1{
2 "code": 400,
3 "message": "参数错误",
4 "error": {
5 "field": "email",
6 "reason": "邮箱格式不正确"
7 },
8 "timestamp": 1706227200000,
9 "requestId": "req_1234567890"
10}

2.3 状态码

HTTP状态码说明
状态码说明常见原因
200OK - 请求成功正常返回
201Created - 创建成功资源创建成功
400Bad Request - 请求错误参数格式错误
401Unauthorized - 未授权Token无效或过期
403Forbidden - 禁止访问权限不足
404Not Found - 资源不存在请求的资源不存在
429Too Many Requests - 请求过多超过限流阈值
500Internal Server Error - 服务器错误服务器内部异常

2.4 业务状态码

CodeMessage说明
1000成功请求处理成功
1001参数错误请求参数不正确
1002认证失败Token无效或过期
1003权限不足无权限访问该资源
1004资源不存在请求的资源不存在
1005操作失败业务操作失败
1006重复操作资源已存在或重复操作
1007限流限制请求频率超过限制

三、认证授权

3.1 获取Token

接口地址POST /auth/login

请求参数

json
1{
2 "username": "user@example.com",
3 "password": "P@ssw0rd123",
4 "grant_type": "password"
5}

响应示例

json
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_tokenstring刷新令牌

响应示例

json
1{
2 "code": 200,
3 "message": "Token刷新成功",
4 "data": {
5 "access_token": "新的访问令牌",
6 "expires_in": 7200
7 }
8}

3.3 Token使用

在请求头中携带Token:

http
1GET /api/users/profile HTTP/1.1
2Host: api.example.com
3Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
4Content-Type: application/json

四、用户管理接口

4.1 用户注册

接口说明:用户通过邮箱注册新账号

请求方式POST

接口地址/users/register

是否需要认证:否

请求参数

参数名类型必填说明示例
emailstring邮箱地址user@example.com
passwordstring密码(8-20位,包含字母和数字)P@ssw0rd123
usernamestring用户名(3-20位)zhangsan
phonestring手机号13800138000
captchastring验证码1234

请求示例

bash
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 }'

响应示例

json
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}

错误响应

json
1{
2 "code": 1001,
3 "message": "参数错误",
4 "error": {
5 "field": "email",
6 "reason": "邮箱已被注册"
7 }
8}

4.2 获取用户信息

接口说明:获取当前登录用户的详细信息

请求方式GET

接口地址/users/profile

是否需要认证:是(需要Bearer Token)

请求参数:无

请求示例

bash
1curl -X GET "https://api.example.com/v1/users/profile" \
2 -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

响应示例

json
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)

请求参数

参数名类型必填说明
nicknamestring昵称
avatarstring头像URL
genderstring性别:male/female/other
birthdaystring生日(YYYY-MM-DD)
addressobject地址信息

请求示例

json
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}

响应示例

json
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)

业务流程

请求参数

json
1{
2 "items": [
3 {
4 "productId": 10001,
5 "quantity": 2,
6 "price": 99.99
7 },
8 {
9 "productId": 10002,
10 "quantity": 1,
11 "price": 199.99
12 }
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}

响应示例

json
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.98
18 },
19 {
20 "productId": 10002,
21 "productName": "商品B",
22 "quantity": 1,
23 "price": 199.99,
24 "subtotal": 199.99
25 }
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)

请求参数

参数名类型必填说明默认值
pageint页码(从1开始)1
pageSizeint每页数量(1-100)10
statusstring订单状态筛选all
keywordstring搜索关键词-
startDatestring开始日期-
endDatestring结束日期-

订单状态值

订单状态说明
状态值中文名称说明
pending_payment待支付订单已创建,等待支付
paid已支付支付完成,等待发货
shipped已发货商品已发出,等待收货
completed已完成订单已完成
cancelled已取消订单已取消
refunding退款中正在处理退款
refunded已退款退款已完成

请求示例

bash
1curl -X GET "https://api.example.com/v1/orders?page=1&pageSize=10&status=paid" \
2 -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

响应示例

json
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": 5
22 }
23 }
24}

六、分页查询规范

6.1 请求参数

所有列表查询接口统一使用以下分页参数:

参数名类型必填说明默认值
pageint页码(从1开始)1
pageSizeint每页数量10
sortBystring排序字段-
sortOrderstring排序方向:asc/descdesc

6.2 响应格式

json
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": false
13 }
14 }
15}

七、错误处理

7.1 错误响应格式

json
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 常见错误码

CodeMessage解决方案
1001参数错误检查请求参数格式
1002Token无效重新登录获取Token
1003权限不足联系管理员分配权限
1004资源不存在检查资源ID是否正确
1005操作失败查看详细错误信息
1006重复操作避免重复提交
1007请求限流降低请求频率

八、限流说明

8.1 限流策略

接口限流配置
接口类型限流规则超限后行为
登录注册10次/分钟/IP返回429状态码,60秒后重试
查询接口100次/分钟/用户返回429状态码,1分钟后重试
修改接口50次/分钟/用户返回429状态码,1分钟后重试
支付接口10次/分钟/用户返回429状态码,5分钟后重试

8.2 限流响应

json
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

回调参数

json
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}

验证签名

javascript
1const crypto = require('crypto');
2
3function verifySign(data, sign, secret) {
4 const str = Object.keys(data)
5 .sort()
6 .map(key => `${key}=${data[key]}`)
7 .join('&');
8
9 const hash = crypto
10 .createHmac('sha256', secret)
11 .update(str)
12 .digest('hex');
13
14 return hash === sign;
15}

十、SDK示例

10.1 JavaScript SDK

javascript
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}
44
45// 使用示例
46const client = new ApiClient('https://api.example.com/v1', 'your_token');
47
48// 获取用户信息
49const profile = await client.getProfile();
50console.log(profile);
51
52// 创建订单
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接口的示例请求。

导入步骤

  1. 下载 API.postman_collection.json
  2. 在Postman中选择 Import
  3. 选择下载的文件导入

11.2 在线调试

访问我们的API在线调试平台:

🔗 https://api-debug.example.com


十二、常见问题

Q1: 如何获取API密钥?

A: 登录开发者平台,在"应用管理"中创建应用并获取密钥。

Q2: Token过期后如何处理?

A: 使用refresh_token调用刷新接口获取新的access_token。

Q3: 如何调试Webhook回调?

A: 可以使用 webhook.sitengrok 进行本地调试。


十三、联系我们

API支持

附录

A. 完整接口列表

查看 接口索引 获取完整的接口列表。

B. 更新日志

v1.0.0 (2025-01-20)

  • 初始版本发布
  • 支持用户管理、订单管理等基础功能

v0.9.0 (2025-01-10)

  • Beta版本测试

评论