Python中requests.get接口数据写入JSON文件不全的问题求助
解决API分页数据完整获取问题
你的问题是因为目标API采用了分页机制,单次GET请求仅返回单页数据(此处为1439条),而X-Total-Count是符合条件的总记录数。要获取全部数据,需要循环请求所有分页并合并结果。
步骤说明及代码实现
确认API分页参数
多数REST API会使用以下两种分页参数模式:page(页码)+per_page(每页条数)offset(偏移量)+limit(每页条数)
以下示例以page+per_page为例,若API采用另一种模式,只需调整params部分即可。
完整获取并写入数据的代码
import requests import json import time username = 'ROAND' password = dbutils.secrets.get("lab-secrets", "ROSecret") base_url = 'https://pit.service.com/api/table' # 初始化存储所有数据的列表 all_data = [] # 请求第一页,获取每页条数和总记录数 response = requests.get(base_url, auth=(username, password)) response.raise_for_status() # 捕获请求错误 first_page = response.json() all_data.extend(first_page) per_page = len(first_page) total_count = int(response.headers['X-Total-Count']) # 计算总页数(向上取整) total_pages = (total_count + per_page - 1) // per_page # 循环请求剩余页面 for page_num in range(2, total_pages + 1): params = { 'page': page_num, 'per_page': per_page # 若为offset模式,替换为: # 'offset': (page_num - 1) * per_page, # 'limit': per_page } response = requests.get(base_url, auth=(username, password), params=params) response.raise_for_status() page_data = response.json() all_data.extend(page_data) # 添加延迟,避免触发API限流 time.sleep(1) # 将合并后的完整数据写入JSON文件 with open('/path/file.json', 'w', encoding='utf-8') as f: json.dump(all_data, f, ensure_ascii=False, indent=2)
关键注意事项
- 参数适配:务必根据目标API文档调整分页参数,若不确定,可尝试在URL后拼接
?per_page=1000(或其他数值),观察返回数据量变化验证参数有效性。 - 错误处理:
response.raise_for_status()会在API返回4xx/5xx错误时抛出异常,避免无效数据混入结果。 - 限流规避:添加
time.sleep()避免短时间内发送大量请求,若API有明确速率限制,需对应调整延迟时长。 - 数据写入:使用
json.dump()而非直接写入response.content,能保证JSON格式规范,同时支持非ASCII字符(如中文)的正确存储。
内容的提问来源于stack exchange,提问作者Roho
相关产品推荐
相关产品推荐

