Python调用API接口实战指南
在当今互联网开发领域,API(应用程序编程接口)已成为系统间数据交互的核心桥梁。本文将通过800字快速讲解使用Python调用API的完整流程,并提供可直接运行的代码示例。
一、基础准备
1. 安装requests库
“`bash
pip install requests
“`
2. 选择测试API
推荐使用免费开放的公共API:
– JSONPlaceholder(模拟REST API)
– OpenWeatherMap(需注册获取API key)
二、核心请求方法
1. GET请求示例
“`python
import requests
response = requests.get(
“https://jsonplaceholder.typicode.com/posts/1”
)
print(response.status_code) 200
print(response.json()) 获取JSON响应
“`
2. POST请求示例
“`python
new_post = {
“title”: “foo”,
“body”: “bar”,
“userId”: 1
}
response = requests.post(
“https://jsonplaceholder.typicode.com/posts”,
json=new_post
)
print(response.json()) 返回创建的资源
“`
三、进阶功能实现
1. 请求头设置
“`python
headers = {
“Authorization”: “Bearer your_token”,
“Content-Type”: “application/json”
}
response = requests.get(
“https://api.example.com/data”,
headers=headers
)
“`
2. 参数传递
“`python
params = {
“q”: “Python”,
“page”: 2,
“sort”: “stars”
}
response = requests.get(
“https://api.github.com/search/repositories”,
params=params
)
“`
3. 异常处理
“`python
try:
response = requests.get(url, timeout=5)
response.raise_for_status() 自动抛出4xx/5xx错误
except requests.exceptions.HTTPError as errh:
print(f”HTTP Error: {errh}”)
except requests.exceptions.Timeout as errt:
print(f”Timeout Error: {errt}”)
except requests.exceptions.RequestException as err:
print(f”Request Error: {err}”)
“`
四、完整实战案例(天气预报API)
“`python
import requests
def get_weather(city, api_key):
base_url = “http://api.openweathermap.org/data/2.5/weather”
params = {
“q”: city,
“appid”: api_key,
“units”: “metric”
}
try:
response = requests.get(base_url, params=params)
response.raise_for_status()
data = response.json()
return {
“temperature”: data[“main”][“temp”],
“humidity”: data[“main”][“humidity”],
“description”: data[“weather”][0][“description”]
}
except Exception as e:
return f”Error fetching data: {str(e)}”
使用示例
api_key = “your_api_key” 注册获取真实key
print(get_weather(“London”, api_key))
“`
五、最佳实践建议
1. 密钥管理:使用环境变量或配置文件存储敏感信息
2. 速率限制:遵守API提供方的调用频率限制
3. 缓存机制:对频繁请求的数据进行本地缓存
4. 日志记录:记录重要请求的详细信息
5. 异步调用:使用aiohttp库提升并发性能
通过掌握这些核心技巧,开发者可以轻松实现与各类API的高效交互。建议通过Postman等工具测试API接口,再转化为Python代码实现。随着实践深入,可进一步学习OAuth认证、WebSocket实时通信等高级主题。