API 使用示例
本页面提供了各种 API 使用的实际示例,帮助开发者快速上手。
🚀 快速开始示例
基础认证
// 设置 API 基础配置
const API_BASE_URL = 'https://api.example.com';
const API_TOKEN = 'your-api-token';
// 创建请求头
const headers = {
'Authorization': `Bearer ${API_TOKEN}`,
'Content-Type': 'application/json'
};
获取数据示例
// 获取用户列表
async function getUsers() {
try {
const response = await fetch(`${API_BASE_URL}/api/users`, {
method: 'GET',
headers: headers
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('获取用户列表失败:', error);
throw error;
}
}
创建数据示例
// 创建新用户
async function createUser(userData) {
try {
const response = await fetch(`${API_BASE_URL}/api/users`, {
method: 'POST',
headers: headers,
body: JSON.stringify(userData)
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('创建用户失败:', error);
throw error;
}
}
// 使用示例
const newUser = {
name: '张三',
email: 'zhangsan@example.com',
role: 'user'
};
createUser(newUser)
.then(user => console.log('用户创建成功:', user))
.catch(error => console.error('创建失败:', error));
🔧 高级示例
批量操作
// 批量创建用户
async function batchCreateUsers(users) {
const results = [];
for (const user of users) {
try {
const result = await createUser(user);
results.push({ success: true, data: result });
} catch (error) {
results.push({ success: false, error: error.message });
}
}
return results;
}
错误处理
// 统一错误处理
class APIClient {
constructor(baseURL, token) {
this.baseURL = baseURL;
this.token = token;
}
async request(endpoint, options = {}) {
const url = `${this.baseURL}${endpoint}`;
const config = {
headers: {
'Authorization': `Bearer ${this.token}`,
'Content-Type': 'application/json',
...options.headers
},
...options
};
try {
const response = await fetch(url, config);
if (!response.ok) {
const errorData = await response.json();
throw new APIError(response.status, errorData.message, errorData);
}
return await response.json();
} catch (error) {
if (error instanceof APIError) {
throw error;
}
throw new APIError(0, '网络请求失败', { originalError: error });
}
}
}
// 自定义错误类
class APIError extends Error {
constructor(status, message, data) {
super(message);
this.name = 'APIError';
this.status = status;
this.data = data;
}
}
📱 不同平台示例
Python 示例
import requests
import json
class APIClient:
def __init__(self, base_url, token):
self.base_url = base_url
self.headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}
def get_users(self, page=1, limit=20):
"""获取用户列表"""
url = f"{self.base_url}/api/users"
params = {'page': page, 'limit': limit}
response = requests.get(url, headers=self.headers, params=params)
response.raise_for_status()
return response.json()
def create_user(self, user_data):
"""创建用户"""
url = f"{self.base_url}/api/users"
response = requests.post(
url,
headers=self.headers,
data=json.dumps(user_data)
)
response.raise_for_status()
return response.json()
# 使用示例
client = APIClient('https://api.example.com', 'your-token')
# 获取用户
users = client.get_users(page=1, limit=10)
print(f"获取到 {len(users['data']['users'])} 个用户")
# 创建用户
new_user = {
'name': '李四',
'email': 'lisi@example.com'
}
result = client.create_user(new_user)
print(f"用户创建成功,ID: {result['data']['id']}")
cURL 示例
# 获取用户列表
curl -X GET "https://api.example.com/api/users?page=1&limit=10" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json"
# 创建用户
curl -X POST "https://api.example.com/api/users" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "王五",
"email": "wangwu@example.com",
"role": "user"
}'
# 更新用户
curl -X PUT "https://api.example.com/api/users/123" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "王五(已更新)",
"email": "wangwu.updated@example.com"
}'
# 删除用户
curl -X DELETE "https://api.example.com/api/users/123" \
-H "Authorization: Bearer YOUR_TOKEN"
🔍 调试和测试
请求日志
// 添加请求日志
class LoggingAPIClient extends APIClient {
async request(endpoint, options = {}) {
console.log(`[API] ${options.method || 'GET'} ${endpoint}`);
console.log('[API] 请求参数:', options.body);
const startTime = Date.now();
try {
const result = await super.request(endpoint, options);
const duration = Date.now() - startTime;
console.log(`[API] 请求成功 (${duration}ms)`);
console.log('[API] 响应数据:', result);
return result;
} catch (error) {
const duration = Date.now() - startTime;
console.error(`[API] 请求失败 (${duration}ms):`, error);
throw error;
}
}
}
单元测试
// Jest 测试示例
describe('API Client', () => {
let client;
beforeEach(() => {
client = new APIClient('https://api.example.com', 'test-token');
});
test('应该能够获取用户列表', async () => {
// Mock fetch
global.fetch = jest.fn().mockResolvedValue({
ok: true,
json: () => Promise.resolve({
code: 200,
data: {
users: [
{ id: 1, name: '测试用户', email: 'test@example.com' }
]
}
})
});
const result = await client.request('/api/users');
expect(result.code).toBe(200);
expect(result.data.users).toHaveLength(1);
expect(fetch).toHaveBeenCalledWith(
'https://api.example.com/api/users',
expect.objectContaining({
headers: expect.objectContaining({
'Authorization': 'Bearer test-token'
})
})
);
});
});
📋 最佳实践
1. 错误处理
- 始终处理网络错误和 HTTP 错误
- 提供有意义的错误信息
- 实现重试机制
2. 性能优化
- 使用连接池
- 实现请求缓存
- 避免不必要的请求
3. 安全考虑
- 安全存储 API Token
- 使用 HTTPS
- 验证响应数据
4. 代码组织
- 创建可复用的 API 客户端类
- 分离配置和业务逻辑
- 添加适当的日志记录