Python调用API循环报错:JSON不存在@odata.nextLink如何处理
问题根因
你代码中直接用response["@odata.nextLink"]的方式读取字段值,当接口分页到最后一页时,返回的JSON结构中不存在@odata.nextLink这个键,Python会直接抛出KeyError异常,不会进入你预期的循环判断逻辑:此时还没到布尔值校验的步骤,索引不存在的键就已经触发报错了。
修复方案
使用字典内置的get()方法读取字段即可,该方法在键不存在时会默认返回None,布尔判断时会识别为假,自动退出循环,符合你原来的设计逻辑。
你也可以选择先判断键是否存在于返回结果中,再进行取值操作,两种写法都可以避免KeyError。
修改后完整代码
# Import Python ODBC module import pyodbc import requests import json import sys cnxn = pyodbc.connect(driver="{ODBC Driver 17 for SQL Server}",server="theplacewherethedatais",database="oneofthosedbthings",uid="u",pwd="pw") cursor = cnxn.cursor() storedProc = "exec GetGroupsAndCompanies" for irow in cursor.execute(storedProc): strObj = str(irow[0]) strGrp = str(irow[1]) print(strObj+" "+strGrp) response = requests.get(irow[2], timeout=300, auth=('u', 'pw')).json() data = response["value"] # 改用get方法读取字段,不存在时默认返回None自动终止循环 while response.get("@odata.nextLink"): response = requests.get(response["@odata.nextLink"], timeout=300, auth=('u', 'pw')).json() data.extend(response["value"]) cnxn.commit() cnxn.close()
额外注意事项
- requests库的timeout参数单位为秒,原代码设置的300000秒相当于83小时,远超过正常接口请求的合理时长,上述代码已调整为300秒(5分钟),你可以根据实际接口响应速度调整。
- 建议可以增加异常捕获逻辑,处理接口请求失败、返回格式异常等边界情况,提升代码稳定性。
内容的提问来源于stack exchange,提问作者Doug Coats
相关产品推荐
相关产品推荐

