You need to enable JavaScript to run this app. Python调用API循环报错:JSON不存在@odata.nextLink如何处理
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 17:27:03