在现代软件开发中,接入第三方API是常见的需求。Python凭借其丰富的库生态和简洁的语法,成为实现API接入的理想选择。下面我将介绍如何使用Python高效接入第三方API。
python
| import requests | |
|---|---|
| def call_api(url, params=None, headers=None, method='GET'): | |
| """基础API调用函数""" | |
| try: | |
| response = requests.request( | |
| method=method, | |
| url=url, | |
| params=params, | |
| headers=headers, | |
| timeout=10 | |
| ) | |
| response.raise_for_status() # 自动处理HTTP错误 | |
| return response.json() # 假设API返回JSON格式 | |
| except requests.exceptions.RequestException as e: | |
| print(f"API调用失败: {e}") | |
| return None | |
| # 示例:调用天气API | |
| weather_url = "api.openweathermap.org/data/2.5/we…" | |
| params = { | |
| 'q': 'Beijing', | |
| 'appid': 'your_api_key_here', | |
| 'units': 'metric' | |
| } | |
| response = call_api(weather_url, params=params) | |
| print(response) |
通过以上方法,您可以构建健壮的Python API客户端,高效安全地接入各种第三方服务。