繁体   English   中英

拨打多个 API 电话 - Python

[英]Make multiple API calls - Python

我经常使用 API 调用来拉取一些客户数据。 但是,每当我尝试提取超过 20 个客户 ID 时,API 就会停止工作。 发生这种情况时,我运行多个 API 调用,将每个 JSON output 转换为 df 和 append 所有数据帧。

当我只需要几个 API 调用时,这很好,但是当我有多个客户 ID 需要提取时,效率会变得低下,因为有时我必须运行 5/10 个单独的 API 调用。

我认为循环可以在这里提供帮助。 鉴于我对 Python 的经验很少,我查看了有关循环 API 的其他问题,但找不到解决方案。

下面是我使用的代码。 我怎样才能进行一个 API 循环调用多个客户 ID(请记住,每次调用有大约 20 个 ID 的限制)并返回一个 dataframe?

谢谢!

#list of customer ids
customer_id = [
"1004rca402itas8470der874",
"1004rca402itas8470der875,
"1004rca402itas8470der876",
"1004rca402itas8470der877",
"1004rca402itas8470der878",
"1004rca402itas8470der879"
]
#API call
payload = {'customer':",".join(customer_id), 'countries':'DE, 'granularity':'daily', 'start_date':'2021-01-01', 'end_date':'2022-03-31'}

response = requests.get('https://api.xxxxxxjxjx.com/t3/customers/xxxxxxxxxxxx?auth_token=xxxxxxxxxxxx', params=payload)

response.status_code
#convert to dataframe
api = response.json()
df = pd.DataFrame(api)
df['sales'] = df['domestic_sales'] + df['international_sales']
df = df[['customer_id','country','date','sales']]
df.head()

这是一般的想法:

# List of dataframes
dfs = []

# List of lists of 20 customer ids each
ids = [customer_id[i:i+20] for i in range(0, len(customer_id), 20)]

# Iterate on 'ids' to call api and store new df in list called 'dfs'
for chunk in ids:
    payload = {
        "customer": ",".join(chunk),
        "countries": "DE",
        "granularity": "daily",
        "start_date": "2021-01-01",
        "end_date": "2022-03-31",
    }
    response = requests.get(
        "https://api.xxxxxxjxjx.com/t3/customers/xxxxxxxxxxxx?auth_token=xxxxxxxxxxxx",
        params=payload,
    )
    dfs.append(pd.DataFrame(response.json()))

# Concat all dataframes
df = dfs[0]
for other_df in dfs[1:]:
    df = pd.concat([df, other_df])

# Additional work
df['sales'] = df['domestic_sales'] + df['international_sales']
df = df[['customer_id','country','date','sales']]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM