【问题标题】:Call API for each element in list为列表中的每个元素调用 API
【发布时间】: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

标签: python json loops


【解决方案1】:

当一个函数遇到return 语句时,它会立即结束。由于您的 return 语句在循环中,因此实际上从未调用其他迭代。

要解决此问题,您可以在循环外创建一个 list,在每次循环迭代时附加到它,然后返回使用该列表创建的 DataFrame:

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)

更简洁的解决方案是使用列表理解:

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])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 2023-03-12
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多