logo

Python接口调用全攻略:从HTTP到函数封装的实践指南

作者:很菜不狗2025.09.25 16:20浏览量:0

简介:本文详细讲解Python中调用接口的两种核心方式:HTTP接口调用与本地接口函数调用,涵盖requests库使用、接口封装、参数处理、错误处理等关键环节,提供完整代码示例与最佳实践。

一、HTTP接口调用的基础实现

1.1 使用requests库发起GET请求

requests库是Python中最常用的HTTP客户端库,其GET请求实现简单高效:

  1. import requests
  2. def call_get_api(url, params=None):
  3. """
  4. 发起GET请求并返回JSON数据
  5. :param url: 接口地址
  6. :param params: 查询参数(字典)
  7. :return: 解析后的JSON数据
  8. """
  9. try:
  10. response = requests.get(url, params=params)
  11. response.raise_for_status() # 检查HTTP错误
  12. return response.json()
  13. except requests.exceptions.RequestException as e:
  14. print(f"GET请求失败: {e}")
  15. return None
  16. # 使用示例
  17. api_url = "https://api.example.com/data"
  18. params = {"page": 1, "size": 10}
  19. result = call_get_api(api_url, params)

1.2 POST请求的实现与数据提交

对于需要提交数据的接口,POST请求更为常用:

  1. def call_post_api(url, data=None, json=None):
  2. """
  3. 发起POST请求
  4. :param url: 接口地址
  5. :param data: 表单数据(字典)
  6. :param json: JSON数据(字典)
  7. :return: 解析后的JSON数据
  8. """
  9. try:
  10. headers = {'Content-Type': 'application/json'} if json else None
  11. response = requests.post(url, data=data, json=json, headers=headers)
  12. response.raise_for_status()
  13. return response.json()
  14. except requests.exceptions.RequestException as e:
  15. print(f"POST请求失败: {e}")
  16. return None
  17. # 使用示例1:表单提交
  18. form_data = {"username": "test", "password": "123456"}
  19. result = call_post_api("https://api.example.com/login", data=form_data)
  20. # 使用示例2:JSON提交
  21. json_data = {"key": "value"}
  22. result = call_post_api("https://api.example.com/api", json=json_data)

1.3 接口调用的最佳实践

  1. 超时设置:添加timeout参数避免长时间等待
    1. response = requests.get(url, timeout=5) # 5秒超时
  2. 重试机制:使用requests.Session保持连接
    1. session = requests.Session()
    2. session.mount('https://', requests.adapters.HTTPAdapter(max_retries=3))
  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)

  1. # 二、接口函数的封装与调用
  2. ## 2.1 基础函数封装
  3. 将接口调用逻辑封装为可复用的函数:
  4. ```python
  5. class APIClient:
  6. def __init__(self, base_url):
  7. self.base_url = base_url
  8. self.session = requests.Session()
  9. def get_data(self, endpoint, params=None):
  10. """GET请求封装"""
  11. url = f"{self.base_url}/{endpoint}"
  12. try:
  13. response = self.session.get(url, params=params, timeout=10)
  14. response.raise_for_status()
  15. return response.json()
  16. except Exception as e:
  17. print(f"获取数据失败: {e}")
  18. return None
  19. def post_data(self, endpoint, data=None, json=None):
  20. """POST请求封装"""
  21. url = f"{self.base_url}/{endpoint}"
  22. try:
  23. headers = {'Content-Type': 'application/json'} if json else None
  24. response = self.session.post(url, data=data, json=json,
  25. headers=headers, timeout=10)
  26. response.raise_for_status()
  27. return response.json()
  28. except Exception as e:
  29. print(f"提交数据失败: {e}")
  30. return None
  31. # 使用示例
  32. client = APIClient("https://api.example.com")
  33. data = client.get_data("users", {"id": 123})
  34. result = client.post_data("orders", json={"product": "book"})

2.2 参数验证与类型提示

Python 3.5+支持类型提示,可增强代码可读性:

  1. from typing import Dict, Optional, Any
  2. class TypedAPIClient:
  3. def __init__(self, base_url: str):
  4. self.base_url = base_url
  5. def get_user(self, user_id: int,
  6. params: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, Any]]:
  7. """获取用户信息"""
  8. endpoint = f"users/{user_id}"
  9. try:
  10. response = requests.get(f"{self.base_url}/{endpoint}",
  11. params=params, timeout=5)
  12. response.raise_for_status()
  13. return response.json()
  14. except requests.exceptions.HTTPError:
  15. print("用户不存在")
  16. return None
  17. except Exception as e:
  18. print(f"请求错误: {e}")
  19. return None
  20. # 使用示例
  21. client = TypedAPIClient("https://api.example.com")
  22. user = client.get_user(123, {"fields": "name,email"})

2.3 异步接口调用

对于高并发场景,可使用aiohttp实现异步调用:

  1. import aiohttp
  2. import asyncio
  3. async def async_get_api(url: str, params: dict = None) -> dict:
  4. """异步GET请求"""
  5. async with aiohttp.ClientSession() as session:
  6. try:
  7. async with session.get(url, params=params) as response:
  8. return await response.json()
  9. except Exception as e:
  10. print(f"异步请求失败: {e}")
  11. return {}
  12. # 使用示例
  13. async def main():
  14. url = "https://api.example.com/data"
  15. result = await async_get_api(url, {"page": 1})
  16. print(result)
  17. asyncio.run(main())

三、常见问题与解决方案

3.1 接口认证失败处理

  1. Token过期:实现自动刷新机制

    1. class TokenManager:
    2. def __init__(self, refresh_url):
    3. self.refresh_url = refresh_url
    4. self.token = None
    5. self.expires = 0
    6. async def get_token(self):
    7. if not self.token or time.time() > self.expires:
    8. # 实现获取新token的逻辑
    9. pass
    10. return self.token
  2. SSL证书验证:生产环境不应禁用验证,开发环境可临时禁用

    1. # 不推荐生产环境使用
    2. response = requests.get(url, verify=False)

3.2 数据格式处理

  1. 日期时间处理:使用arrow库简化操作
    ```python
    import arrow

def parse_api_date(date_str: str) -> arrow.Arrow:
return arrow.get(date_str).to(‘local’)

  1. 2. **复杂嵌套JSON**:使用dataclasses简化处理
  2. ```python
  3. from dataclasses import dataclass
  4. @dataclass
  5. class User:
  6. id: int
  7. name: str
  8. email: str
  9. def parse_user(data: dict) -> User:
  10. return User(**data)

3.3 性能优化技巧

  1. 连接池管理:requests.Session默认使用连接池

    1. session = requests.Session()
    2. # 复用session对象进行多次请求
  2. 批量接口调用:使用asyncio实现并发

    1. async def fetch_multiple(urls: list) -> list:
    2. async with aiohttp.ClientSession() as session:
    3. tasks = [session.get(url) for url in urls]
    4. responses = await asyncio.gather(*tasks)
    5. return [await r.json() for r in responses]

四、完整项目示例

4.1 项目结构

  1. api_client/
  2. ├── __init__.py
  3. ├── client.py # 核心客户端
  4. ├── models.py # 数据模型
  5. ├── exceptions.py # 自定义异常
  6. └── utils.py # 工具函数

4.2 核心实现

  1. # client.py
  2. import requests
  3. from typing import Optional, Dict, Any
  4. from .exceptions import APIError, AuthError
  5. from .models import User, Order
  6. class APIClient:
  7. def __init__(self, base_url: str, api_key: str):
  8. self.base_url = base_url.rstrip('/')
  9. self.api_key = api_key
  10. self.session = requests.Session()
  11. self.session.headers.update({
  12. 'Authorization': f'Bearer {api_key}',
  13. 'Accept': 'application/json'
  14. })
  15. def _validate_response(self, response: requests.Response) -> Dict[str, Any]:
  16. if response.status_code == 401:
  17. raise AuthError("认证失败")
  18. if response.status_code >= 400:
  19. raise APIError(f"请求错误: {response.status_code}")
  20. return response.json()
  21. def get_user(self, user_id: int) -> Optional[User]:
  22. url = f"{self.base_url}/users/{user_id}"
  23. try:
  24. response = self.session.get(url)
  25. data = self._validate_response(response)
  26. return User.from_dict(data)
  27. except APIError as e:
  28. print(f"获取用户失败: {e}")
  29. return None
  30. def create_order(self, order_data: Dict[str, Any]) -> Optional[Order]:
  31. url = f"{self.base_url}/orders"
  32. try:
  33. response = self.session.post(url, json=order_data)
  34. data = self._validate_response(response)
  35. return Order.from_dict(data)
  36. except APIError as e:
  37. print(f"创建订单失败: {e}")
  38. return None

4.3 使用示例

  1. # main.py
  2. from api_client import APIClient
  3. client = APIClient("https://api.example.com", "your_api_key")
  4. # 获取用户
  5. user = client.get_user(123)
  6. if user:
  7. print(f"用户: {user.name}")
  8. # 创建订单
  9. order_data = {
  10. "product_id": 456,
  11. "quantity": 2
  12. }
  13. order = client.create_order(order_data)
  14. if order:
  15. print(f"订单ID: {order.id}")

五、总结与建议

  1. 封装原则:将接口调用逻辑与业务逻辑分离
  2. 错误处理:实现分级错误处理机制
  3. 文档完善:使用Swagger或OpenAPI规范接口文档
  4. 测试覆盖:编写单元测试验证接口调用
  5. 性能监控:添加请求耗时统计和日志记录

通过合理封装接口调用函数,可以显著提升代码的可维护性和复用性。建议根据项目规模选择合适的封装层次,小型项目可采用函数式封装,中大型项目推荐使用面向对象或异步框架实现。

相关文章推荐

发表评论