使用Python的requests库调用API并处理JSON响应的详细步骤
1. 安装request库
pip install requests
2. 发送GET请求
import requests
# 定义API地址
url = "https://api.example.com/data"
# 发送GET请求
response = requests.get(url)
# 检查HTTP状态码
if response.status_code == 200:
# 解析JSON响应
data = response.json()
print("请求成功,数据内容:", data)
else:
print(f"请求失败,状态码:{response.status_code}")
3. 处理URL参数
params = {
"param1": "value1",
"param2": 123
}
response = requests.get(url, params=params)
4. 发送POST请求
payload = {
"key1": "value1",
"key2": "value2"
}
# 发送JSON格式数据
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
# 或者使用data参数(表单格式)
# response = requests.post(url, data=payload)
5. 处理认证
headers = {
"Authorization": "Bearer YOUR_ACCESS_TOKEN",
# 或使用API密钥:
# "X-API-Key": "YOUR_API_KEY"
}
response = requests.get(url, headers=headers)
6. 提取JSON数据中的字段
假设返回的JSON结构如下:
{
"status": "success",
"data": {
"id": 123,
"name": "Example"
}
}
提前数据的python代码:
resp_json = response.json()
# 获取嵌套字段
status = resp_json.get("status")
user_id = resp_json["data"]["id"]
user_name = resp_json["data"].get("name", "默认名称")
print(f"用户ID: {user_id}, 姓名: {user_name}")
7.错误处理
try:
response = requests.get(url, timeout=5) # 设置超时时间
response.raise_for_status() # 自动抛出HTTP错误
data = response.json()
print("解析到的数据:", data)
except requests.exceptions.RequestException as e:
print(f"请求异常:{e}")
except ValueError as e:
print(f"JSON解析失败:{e}")
except KeyError as e:
print(f"JSON字段缺失:{e}")
8. 高级用法:处理分页API
page = 1
all_data = []
while True:
response = requests.get(f"{url}?page={page}")
page_data = response.json()
if not page_data["results"]:
break
all_data.extend(page_data["results"])
page += 1
print(f"总收集到{len(all_data)}条数据")
【关键点:】
1. HTTP方法选择:根据API要求使用
get()
,post()
,put()
,delete()
2. 参数传递:
GET参数用
params
POST数据用
data
(表单)或json
(JSON格式)3. 请求头设置:通过
headers
参数添加认证信息4. 响应处理:
检查
status_code
使用
.json()
解析响应内容使用
.get()
方法避免 KeyError5. 异常处理:捕获网络错误和解析错误