用 requests 调 API:发请求、收数据、处理错误
Python 装好之后,最实用的事情之一就是调 API。requests 是 Python 最流行的 HTTP 库,几行代码就能发请求、拿数据。这篇笔记从装包开始,覆盖 GET、POST、JSON 解析和错误处理。
一、安装 requests
pip install requests
装完验证:
python3 -c "import requests; print(requests.__version__)"
二、GET 请求:最基础的用法
import requests
resp = requests.get("https://httpbin.org/get")
print(resp.status_code) # 200
print(resp.text) # 原始响应文本
print(resp.json()) # 直接解析为 Python 字典
带参数
# 查询参数
params = {"q": "python", "lang": "zh"}
resp = requests.get("https://api.example.com/search", params=params)
# 实际请求: /search?q=python&lang=zh
带请求头
headers = {"Authorization": "Bearer your_token"}
resp = requests.get("https://api.example.com/data", headers=headers)
三、POST 请求:发送数据
import requests, json
data = {"name": "小明", "age": 25}
resp = requests.post(
"https://api.example.com/users",
json=data # 自动设置 Content-Type: application/json
)
print(resp.status_code) # 201
print(resp.json()) # 服务端返回的数据
💡 提示:用
json=data 而不是 data=json.dumps(data),requests 会自动序列化并设置正确的 Content-Type。四、超时设置(必做)
不加超时的请求可能永远挂着。生产代码里必须加:
resp = requests.get("https://slow-site.com", timeout=10) # 10秒超时
五、错误处理
import requests
try:
resp = requests.get("https://api.example.com/data", timeout=10)
resp.raise_for_status() # 4xx/5xx 时抛异常
except requests.exceptions.Timeout:
print("请求超时")
except requests.exceptions.ConnectionError:
print("连不上服务器")
except requests.exceptions.HTTPError as e:
print(f"HTTP 错误: {e.response.status_code}")
except requests.exceptions.RequestException as e:
print(f"其他错误: {e}")
检查状态码
if resp.status_code == 200:
data = resp.json()
elif resp.status_code == 401:
print("未授权,检查 token")
elif resp.status_code == 404:
print("资源不存在")
else:
print(f"意外状态码: {resp.status_code}")
六、完整示例:查天气
import requests
def get_weather(city):
"""查城市天气(示例 API)"""
try:
resp = requests.get(
"https://api.open-meteo.com/v1/forecast",
params={"latitude": 31.23, "longitude": 121.47,
"current": "temperature,weather_code"},
timeout=10
)
resp.raise_for_status()
data = resp.json()
return data["current"]["temperature"]
except Exception as e:
return f"查询失败: {e}"
temp = get_weather("上海")
print(f"上海当前温度: {temp}°C")
七、Session:复用连接
连续调同一个 API 时,用 Session 复用 TCP 连接,更快:
with requests.Session() as s:
s.headers["Authorization"] = "Bearer token"
r1 = s.get("https://api.example.com/a")
r2 = s.get("https://api.example.com/b")
# 两次请求复用同一个连接