首页 > 解决方案 > 将 for 循环值传递给 API 调用字段

问题描述

我需要从 for 循环中获取多个值并将它们传递给 api 调用。我这样做的最佳方法是什么?

引用的值是“id”,我需要它们中的每一个来填充 api 调用中的 id 要求。

*** 我的 for 循环

response = json.loads(z)

for d in response:
    for key, value in d['to'].items():
        if key == 'id':
            print(value)

*** API 调用

id = '' # str |
content_type = 'application/json' # str |  (default to application/json)
accept = 'application/json' # str |  (default to application/json)
fields = '' # str | Use a space seperated string of field parameters to include the data in the response. If omitted, the default list of fields will be returned.  (optional) (default to )
filter = 'filter_example' # str | A filter to apply to the query. (optional)
x_org_id = '' # str |  (optional) (default to )



api_response = api_instance.systemusers_get(id, content_type, accept, fields=fields, filter=filter, x_org_id=x_org_id)

标签: pythonapifor-loop

解决方案


正如您自己指出的那样,您需要一个字符串。因此,当您遍历它们时,您必须将这些 id 添加到某个字符串中。所以让我们从创建一个空字符串开始。然后,当我们循环时,我们可以将它连接到字符串,而不是打印 ID

string = ""
for d in response:
    for key, value in d['to'].items():
        if key == 'id':
            string += value

然后:

id = string

当然,现在我不知道该字符串对于该特定 API 需要采用什么格式。但是您应该能够使模式适应,例如,如果需要,用逗号分隔值。

(注意,我在这个问题的上下文中使用名称字符串来明确,但显然想出了一个更好的变量名称)

编辑:如何进行多个 API 调用

如果每次 API 调用只能发送一个 ID,那么您可以做两件事。也可以在循环中进行调用,或者将此 ID 保存到列表中。无论哪种情况,如果您将 API 调用包装到一个函数中,都会有所帮助:

def make_api_call(id)
    id = id
    content_type = 'application/json' # str |  (default to application/json)
    accept = 'application/json' # str |  (default to application/json)
    fields = '' # str | Use a space seperated string of field parameters to include the data in the response. If omitted, the default list of fields will be returned.  (optional) (default to )
    filter = 'filter_example' # str | A filter to apply to the query. (optional)
    x_org_id = '' # str |  (optional) (default to )
    api_response = api_instance.systemusers_get(id, content_type, accept, fields=fields, filter=filter, x_org_id=x_org_id)

现在,您可以像这样在循环中调用它:

for d in response:
    for key, value in d['to'].items():
        if key == 'id':
            make_api_call(value)

或者您可以构建一个列表,然后在该列表上运行调用:

all_ids = []

for d in response:
    for key, value in d['to'].items():
        if key == 'id':
            all_ids.append(value)

for id in all_ids:
    make_api_call(id)

(注意,我使用变量名 'id' 与问题相同。但是首选 '_id',因为 'id' 是内置的。)


推荐阅读