1

示例 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”等等..

新 URL 将具有以下格式

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 进行分页并获取 a 中的所有数据df,并将其作为上述函数的一部分返回。

我无法理解此处提供的其他一些答案,所以我想为任何重复道歉。感谢您的帮助和建议。

4

1 回答 1

2

我是否正确理解您需要一次又一次地阅读 API,直到您不再取回任何数据?你可以这样做。该函数get_data()只会将所有请求的所有行作为一个迭代器返回。从调用函数来看,这看起来就像一个长列表。

但是对于 100,000 行,这将需要很长时间。因为它会读取每个请求 10 行,所以是 10,000 个请求一个接一个。

def get_data(name):
    csr = ""
    baseurl = "https://myurl123.com/api/V2/data/{}".format(name)
    headers = {
        'Authorization': 'ApiKey xyz123',
        'Content-Type': 'application/json'
    }

    while True:
        url = "{}?size=10&cursor={}".format(baseurl, csr)
        res = requests.request("GET", url, headers=headers, data=payload)
        res.raise_for_status()
        data = res.json()
        if not data["Data"]:
            break
        crs = data["Cursor"]

        for row in data["Data"]["City"]:
            yield row

def get_df(name):
    data = get_data(name)

    df = pd.read_json(StringIO(json.dumps(list(data))), orient='records')
    df.reset_index(drop=True, inplace=True)

    return df
于 2021-03-03T16:58:48.503 回答