簡體   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