【发布时间】:2021-06-02 02:48:00
【问题描述】:
示例 JSON 响应
{
"Data": {
"City": [
{
"loc": "Sector XYZ",
"Country": "AUS",
},
{
.
.
.
.
.
},
]
},
"Meta": {},
"ResourceType": 40,
"StatusCode": 200,
"Message": null,
"Cursor": "apicursor-ad39609e-5fb2-4a66-9402-6def95e75655",
]
}
光标是动态的,每次分页响应后都会发生变化;下一个可能是“apicursor-53ee8993-022c-41df-8be7-9bdedfd91e52”等等..
新网址将采用以下格式
https://myurl123.com/api/V2/data/{}?size=10&cursor=apicursor-53ee8993-022c-41df-8be7-9bdedfd91e52
我无法确定如何对响应进行分页并将其附加到非常大的数据集的数据框中。这是我尝试过的,但这不包括分页。
def foo(name):
url = "https://myurl123.com/api/V2/data/{}?size=10".format(name)
print(url)
headers = {
'Authorization': 'ApiKey xyz123',
'Content-Type': 'application/json'
}
response = requests.request("GET", url, headers=headers, data=payload)
try:
x = response.json()
xs = next(iter(x['Data'].values()))
df = pd.read_json(StringIO(json.dumps(xs)), orient='records')
df.reset_index(drop=True, inplace=True)
return df
except:
print('fetch failed')
我只想对 API 进行分页并获取 df 中的所有数据,并将其作为上述函数的一部分返回。
我无法理解此处提供的其他一些答案,因此对于任何重复,我深表歉意。感谢您的帮助和建议。
【问题讨论】:
-
你有什么错误吗?好吧,您不知道,因为您将整个事情包装成一个通用的 try-except 块:)。首先删除它,然后查看错误消息的内容。也许将其添加到您的问题中。
-
@C14L 我没有收到任何错误,但这仅返回前 10 行(就数据框而言) 编辑:如果我从 URL 中删除 size 参数,我会得到前 100,000 行,我猜这是由于设计限制。无论如何,我仍然需要在这里进行分页
标签: python json pandas api pagination