【发布时间】:2019-10-10 13:07:58
【问题描述】:
我有一个包含超过 1000 个 ID 的列表,我想为列表中的每个元素调用一个具有不同端点的 API。 示例:
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)。我希望函数返回我在函数参数中定义的端点的 customerlist 中每个 ID 的值。
我找到了this - 可能相关的 - 问题,但我无法弄清楚我的问题。
可能有一个我没有看到的简单解决方案,因为我刚开始使用 Python。谢谢。
【问题讨论】:
-
看来你的缩进是错误的。函数
get_data末尾的return语句是for循环的inside,它在第一个循环之后立即终止函数。 -
将
return更改为yield