循环调用API

问题描述 投票:0回答:1

我目前正在通过 API 调用从 API 中提取数据,显然可以从 API 调用中提取的数据量是有限的。因此,我必须循环浏览页面,但我尝试过的所有内容要么永远循环,要么出错并给我 JSONDecodeError: [Errno Expecting Value] : 0.

这是当有下一页时 json 文件的样子:

     {'Data': {'XRefCode': 'EarningsDeductionAPi',
  'Rows': [{...]},
 'Paging': {'Next': 'NextURL'}}

这是我当前的代码:

data = []

response = requests.get('URL', headers=headersAPI, params=params, verify=True)
api_response = response.json()

while api_response['Paging']['Next']:
    api_response = requests.get(api_response['Paging']['Next']).json()
    data.extend(api_response['Data']['Rows'])

循环访问此 API 调用的所有页面的最佳方式是什么?

python api
1个回答
0
投票

我认为它会无限页,因为当前页无法知道下一页是否为空。所以你应该在 while 循环中检查

len(api_response['Rows'])>0
而不是检查
api_response['Paging']['Next']
,如下所示:

while len(api_response['Rows'])>0: 
    api_response = requests.get(api_response['Paging']['Next']).json()
    data.extend(api_response['Data']['Rows'])
© www.soinside.com 2019 - 2024. All rights reserved.