API接口循环请求仅获单个JSON响应,其余返回500错误求助
问题根源
你遇到的500错误是因为URL拼接逻辑错误:循环中每次执行url += '?ids=' + ...会不断在原URL后追加新参数,导致后续请求的URL格式完全非法。比如第一次请求后URL变成xxx?ids=1,第二次就变成xxx?ids=1?ids=2,这种错误格式的请求服务器无法解析,直接返回500错误。
修正后的代码
先把基础API URL单独存为变量,每次循环都基于基础URL重新拼接参数,而非在原URL上累加:
# 替换为你的实际API基础地址 base_url = "你的API基础URL" df_filter = spark.sql("""select distinct ID from filter_view""") listOfRows = df_filter.rdd.collect() # 用for循环替代while,代码更简洁 for row in listOfRows: # 每次循环生成正确的请求URL url = f"{base_url}?ids={row.ID}" response = requests.get(url, headers=headers) if response.status_code == 200: json_response = response.json() df2 = pd.json_normalize(json_response, record_path=['entities']) display(df2) else: print(f"Error: HTTP status code {response.status_code},请求ID:{row.ID}")
额外优化建议
- 异常捕获:添加
try-except块处理网络异常(超时、连接失败等),避免程序直接崩溃:
for row in listOfRows: url = f"{base_url}?ids={row.ID}" try: response = requests.get(url, headers=headers, timeout=10) response.raise_for_status() # 自动抛出HTTP错误异常 json_response = response.json() df2 = pd.json_normalize(json_response, record_path=['entities']) display(df2) except requests.exceptions.RequestException as e: print(f"请求ID {row.ID} 失败:{str(e)}")
- 批量请求(若API支持):多数API允许用逗号分隔多个ID一次性请求(如
?ids=1,2,3),可减少请求次数、提升效率:
# 提取所有ID并转为字符串列表 id_list = [str(row.ID) for row in listOfRows] # 拼接批量请求URL url = f"{base_url}?ids={','.join(id_list)}" response = requests.get(url, headers=headers) if response.status_code == 200: json_response = response.json() df2 = pd.json_normalize(json_response, record_path=['entities']) display(df2) else: print(f"批量请求失败:HTTP status code {response.status_code}")
内容的提问来源于stack exchange,提问作者Arun.K
相关产品推荐
相关产品推荐

