Python接口调用全攻略:从HTTP到函数封装的实践指南
2025.09.25 16:20浏览量:0简介:本文详细讲解Python中调用接口的两种核心方式:HTTP接口调用与本地接口函数调用,涵盖requests库使用、接口封装、参数处理、错误处理等关键环节,提供完整代码示例与最佳实践。
一、HTTP接口调用的基础实现
1.1 使用requests库发起GET请求
requests库是Python中最常用的HTTP客户端库,其GET请求实现简单高效:
import requests
def call_get_api(url, params=None):
"""
发起GET请求并返回JSON数据
:param url: 接口地址
:param params: 查询参数(字典)
:return: 解析后的JSON数据
"""
try:
response = requests.get(url, params=params)
response.raise_for_status() # 检查HTTP错误
return response.json()
except requests.exceptions.RequestException as e:
print(f"GET请求失败: {e}")
return None
# 使用示例
api_url = "https://api.example.com/data"
params = {"page": 1, "size": 10}
result = call_get_api(api_url, params)
1.2 POST请求的实现与数据提交
对于需要提交数据的接口,POST请求更为常用:
def call_post_api(url, data=None, json=None):
"""
发起POST请求
:param url: 接口地址
:param data: 表单数据(字典)
:param json: JSON数据(字典)
:return: 解析后的JSON数据
"""
try:
headers = {'Content-Type': 'application/json'} if json else None
response = requests.post(url, data=data, json=json, headers=headers)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"POST请求失败: {e}")
return None
# 使用示例1:表单提交
form_data = {"username": "test", "password": "123456"}
result = call_post_api("https://api.example.com/login", data=form_data)
# 使用示例2:JSON提交
json_data = {"key": "value"}
result = call_post_api("https://api.example.com/api", json=json_data)
1.3 接口调用的最佳实践
- 超时设置:添加timeout参数避免长时间等待
response = requests.get(url, timeout=5) # 5秒超时
- 重试机制:使用requests.Session保持连接
session = requests.Session()
session.mount('https://', requests.adapters.HTTPAdapter(max_retries=3))
- 认证处理:支持Basic Auth和Token认证
```python
from requests.auth import HTTPBasicAuth
response = requests.get(url, auth=HTTPBasicAuth(‘user’, ‘pass’))
或使用Bearer Token
headers = {‘Authorization’: ‘Bearer your_token’}
response = requests.get(url, headers=headers)
# 二、接口函数的封装与调用
## 2.1 基础函数封装
将接口调用逻辑封装为可复用的函数:
```python
class APIClient:
def __init__(self, base_url):
self.base_url = base_url
self.session = requests.Session()
def get_data(self, endpoint, params=None):
"""GET请求封装"""
url = f"{self.base_url}/{endpoint}"
try:
response = self.session.get(url, params=params, timeout=10)
response.raise_for_status()
return response.json()
except Exception as e:
print(f"获取数据失败: {e}")
return None
def post_data(self, endpoint, data=None, json=None):
"""POST请求封装"""
url = f"{self.base_url}/{endpoint}"
try:
headers = {'Content-Type': 'application/json'} if json else None
response = self.session.post(url, data=data, json=json,
headers=headers, timeout=10)
response.raise_for_status()
return response.json()
except Exception as e:
print(f"提交数据失败: {e}")
return None
# 使用示例
client = APIClient("https://api.example.com")
data = client.get_data("users", {"id": 123})
result = client.post_data("orders", json={"product": "book"})
2.2 参数验证与类型提示
Python 3.5+支持类型提示,可增强代码可读性:
from typing import Dict, Optional, Any
class TypedAPIClient:
def __init__(self, base_url: str):
self.base_url = base_url
def get_user(self, user_id: int,
params: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, Any]]:
"""获取用户信息"""
endpoint = f"users/{user_id}"
try:
response = requests.get(f"{self.base_url}/{endpoint}",
params=params, timeout=5)
response.raise_for_status()
return response.json()
except requests.exceptions.HTTPError:
print("用户不存在")
return None
except Exception as e:
print(f"请求错误: {e}")
return None
# 使用示例
client = TypedAPIClient("https://api.example.com")
user = client.get_user(123, {"fields": "name,email"})
2.3 异步接口调用
对于高并发场景,可使用aiohttp实现异步调用:
import aiohttp
import asyncio
async def async_get_api(url: str, params: dict = None) -> dict:
"""异步GET请求"""
async with aiohttp.ClientSession() as session:
try:
async with session.get(url, params=params) as response:
return await response.json()
except Exception as e:
print(f"异步请求失败: {e}")
return {}
# 使用示例
async def main():
url = "https://api.example.com/data"
result = await async_get_api(url, {"page": 1})
print(result)
asyncio.run(main())
三、常见问题与解决方案
3.1 接口认证失败处理
Token过期:实现自动刷新机制
class TokenManager:
def __init__(self, refresh_url):
self.refresh_url = refresh_url
self.token = None
self.expires = 0
async def get_token(self):
if not self.token or time.time() > self.expires:
# 实现获取新token的逻辑
pass
return self.token
SSL证书验证:生产环境不应禁用验证,开发环境可临时禁用
# 不推荐生产环境使用
response = requests.get(url, verify=False)
3.2 数据格式处理
- 日期时间处理:使用arrow库简化操作
```python
import arrow
def parse_api_date(date_str: str) -> arrow.Arrow:
return arrow.get(date_str).to(‘local’)
2. **复杂嵌套JSON**:使用dataclasses简化处理
```python
from dataclasses import dataclass
@dataclass
class User:
id: int
name: str
email: str
def parse_user(data: dict) -> User:
return User(**data)
3.3 性能优化技巧
连接池管理:requests.Session默认使用连接池
session = requests.Session()
# 复用session对象进行多次请求
批量接口调用:使用asyncio实现并发
async def fetch_multiple(urls: list) -> list:
async with aiohttp.ClientSession() as session:
tasks = [session.get(url) for url in urls]
responses = await asyncio.gather(*tasks)
return [await r.json() for r in responses]
四、完整项目示例
4.1 项目结构
api_client/
├── __init__.py
├── client.py # 核心客户端
├── models.py # 数据模型
├── exceptions.py # 自定义异常
└── utils.py # 工具函数
4.2 核心实现
# client.py
import requests
from typing import Optional, Dict, Any
from .exceptions import APIError, AuthError
from .models import User, Order
class APIClient:
def __init__(self, base_url: str, api_key: str):
self.base_url = base_url.rstrip('/')
self.api_key = api_key
self.session = requests.Session()
self.session.headers.update({
'Authorization': f'Bearer {api_key}',
'Accept': 'application/json'
})
def _validate_response(self, response: requests.Response) -> Dict[str, Any]:
if response.status_code == 401:
raise AuthError("认证失败")
if response.status_code >= 400:
raise APIError(f"请求错误: {response.status_code}")
return response.json()
def get_user(self, user_id: int) -> Optional[User]:
url = f"{self.base_url}/users/{user_id}"
try:
response = self.session.get(url)
data = self._validate_response(response)
return User.from_dict(data)
except APIError as e:
print(f"获取用户失败: {e}")
return None
def create_order(self, order_data: Dict[str, Any]) -> Optional[Order]:
url = f"{self.base_url}/orders"
try:
response = self.session.post(url, json=order_data)
data = self._validate_response(response)
return Order.from_dict(data)
except APIError as e:
print(f"创建订单失败: {e}")
return None
4.3 使用示例
# main.py
from api_client import APIClient
client = APIClient("https://api.example.com", "your_api_key")
# 获取用户
user = client.get_user(123)
if user:
print(f"用户: {user.name}")
# 创建订单
order_data = {
"product_id": 456,
"quantity": 2
}
order = client.create_order(order_data)
if order:
print(f"订单ID: {order.id}")
五、总结与建议
通过合理封装接口调用函数,可以显著提升代码的可维护性和复用性。建议根据项目规模选择合适的封装层次,小型项目可采用函数式封装,中大型项目推荐使用面向对象或异步框架实现。
发表评论
登录后可评论,请前往 登录 或 注册