问题描述
我有一个包含1000多个ID的列表,并且我想为该列表的每个元素调用具有不同终结点的API.示例:
I have a list with over 1000 IDs and I want to call an API with different endpoints for every element of the list.Example:
customerlist = [803818, 803808, 803803,803738,803730]
我尝试了以下操作:
import json
import requests
import pandas as pd
API_BASEURL = "https://exampleurl.com/"
API_TOKEN = "abc"
HEADERS = {'content-type' : 'application/json',
'Authorization': API_TOKEN }
def get_data(endpoint):
for i in customerlist:
api_endpoint = endpoint
params = {'customerid' : i}
response = requests.get(f"{API_BASEURL}/{api_endpoint}",
params = params,
headers = HEADERS)
if response.status_code == 200:
res = json.loads(response.text)
else:
raise Exception(f'API error with status code {response.status_code}')
res= pd.DataFrame([res])
return res
get_data(endpointexample)
这有效,但它只返回列表第一个元素的值 (803818).我希望该函数返回客户列表中我在函数参数中定义的端点的每个ID的值.
This works, but it only returns the values for the first element of the list (803818). I want the function to return the values for every ID from customerlist for the endpoint I defined in the function argument.
我发现了这个-可能是相关的-问题,但我无法弄清楚我的问题.
I found this - possibly related - question, but I couldn't figure my problem out.
对于这个问题,可能是一个简单的解决方案,因为我只是从Python入手.谢谢.
There is probably an easy solution for this which I am not seeing, as I am just starting with Python. Thanks.
推荐答案
当函数点击 return
语句时,它立即完成.由于您的 return
语句处于循环中,因此其他迭代永远不会真正被调用.
The moment a function hits a return
statement, it immediately finishes. Since your return
statement is in the loop, the other iterations never actually get called.
要解决此问题,您可以在循环外创建一个 list
,在每次循环迭代时将其添加到该列表中,然后返回使用该列表创建的DataFrame:
To fix, you can create a list
outside the loop, append to it every loop iteration, and then return the DataFrame created with that list:
def get_data(endpoint):
responses = []
for i in customerlist:
api_endpoint = endpoint
params = {'customerid' : i}
response = requests.get(f"{API_BASEURL}/{api_endpoint}",
params = params,
headers = HEADERS)
if response.status_code == 200:
res = json.loads(response.text)
else:
raise Exception(f'API error with status code {response.status_code}')
responses.append(res)
return pd.DataFrame(responses)
一种更简洁的解决方案是使用列表理解:
A much cleaner solution would be to use list comprehension:
def get_data(endpoint, i):
api_endpoint = endpoint
params = {'customerid' : i}
response = requests.get(f"{API_BASEURL}/{api_endpoint}",
params = params,
headers = HEADERS)
if response.status_code == 200:
res = json.loads(response.text)
else:
raise Exception(f'API error with status code {response.status_code}')
return res
responses = pd.DataFrame([get_data(endpoint, i) for i in customerlist])
这篇关于为列表中的每个元素调用API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!