Python API调用实战
学习API请求 · 难度:高级 · +15XP
Python API 调用实战
在现代 Web 开发中,调用 RESTful API 获取或提交数据是非常常见的需求。Python 的 requests 库是进行 HTTP 请求最流行的工具。本节将演示如何使用 requests 库与各种 API 接口进行交互,包括 GET、POST、认证、异常处理等完整流程。
安装与基本 GET 请求
# pip install requests
import requests
# 发送 GET 请求获取数据
response = requests.get('https://api.github.com/users/python')
print(response.status_code) # 200 表示成功
print(response.headers['Content-Type']) # application/json; charset=utf-8
# 解析 JSON 响应
data = response.json()
print(f"用户名: {data['login']}")
print(f"粉丝数: {data['followers']}")
带参数的 GET 请求
import requests
# 使用 params 参数(推荐方式)
params = {
'q': 'python',
'page': 1,
'per_page': 20
}
response = requests.get('https://api.example.com/search', params=params)
print(response.url) # 查看完整 URL
POST 请求提交数据
import requests
# 发送 JSON 数据
payload = {
'title': 'Python 教程',
'content': '学习 Python 异步编程',
'tags': ['python', 'async']
}
response = requests.post(
'https://jsonplaceholder.typicode.com/posts',
json=payload # 自动设置 Content-Type 为 application/json
)
print(response.status_code) # 201 Created
print(response.json())
请求头与认证
import requests
# 自定义请求头
headers = {
'User-Agent': 'MyApp/1.0',
'Authorization': 'Bearer your_api_token_here'
}
response = requests.get(
'https://api.example.com/protected/resource',
headers=headers
)
# HTTP 基本认证
response = requests.get(
'https://api.example.com/admin',
auth=('username', 'password')
)
异常处理与超时设置
import requests
from requests.exceptions import RequestException, Timeout
try:
response = requests.get(
'https://api.example.com/data',
timeout=10 # 设置超时时间(秒)
)
response.raise_for_status() # 检查 HTTP 错误
data = response.json()
print(f'获取到 {len(data)} 条记录')
except Timeout:
print('请求超时,请检查网络连接')
except RequestException as e:
print(f'请求异常: {e}')
except ValueError:
print('JSON 解析失败')
常见 HTTP 状态码速查
| 状态码 | 含义 |
|---|---|
| 200 | 请求成功 |
| 201 | 资源创建成功 |
| 204 | 成功但无返回内容 |
| 400 | 请求参数错误 |
| 401 | 未认证 |
| 403 | 无权限 |
| 404 | 资源不存在 |
| 500 | 服务器内部错误 |