简体   繁体   English

拨打多个 API 电话 - Python

[英]Make multiple API calls - Python

I often use an API call to pull some customer data.我经常使用 API 调用来拉取一些客户数据。 However, whenever I try to pull more than 20 customer ids, the API stops working.但是,每当我尝试提取超过 20 个客户 ID 时,API 就会停止工作。 When this happens, I run multiple API calls, transform each JSON output into a df and append all the dataframes together.发生这种情况时,我运行多个 API 调用,将每个 JSON output 转换为 df 和 append 所有数据帧。

That is fine when I need just a couple of API calls, but becomes inefficient when I have several customer ids to pull, as sometimes I have to run 5/10 separate API calls.当我只需要几个 API 调用时,这很好,但是当我有多个客户 ID 需要提取时,效率会变得低下,因为有时我必须运行 5/10 个单独的 API 调用。

I thought a loop could help here.我认为循环可以在这里提供帮助。 Given I have little experience with Python, I had a look at other questions on looping APIs, but I couldn't find a solution.鉴于我对 Python 的经验很少,我查看了有关循环 API 的其他问题,但找不到解决方案。

Below is the code I use.下面是我使用的代码。 How can I make a single API call that loops through several customer ids (keeping in mind that there's a limit of circa 20 ids per call) and returns a single dataframe?我怎样才能进行一个 API 循环调用多个客户 ID(请记住,每次调用有大约 20 个 ID 的限制)并返回一个 dataframe?

Thanks!谢谢!

#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()

Here is the general idea:这是一般的想法:

# 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