为请求 API 负载创建变量字符串

Create variable string for request API payload

我有一个 URL 的列表,它们都引用图像。我想遍历列表并调用接受这些 URL 的 face recognition API。要调用 API,我需要提供负载字典。但是,API 中的示例代码需要以下形式的有效负载字典:

payload = "{\"url\":\"https://inferdo.com/img/face-3.jpg\",\"accuracy_boost\":3}"

此示例有效负载字典中的 URL 在我的列表中将如下所示:

list_of_urls = ["https://inferdo.com/img/face-3.jpg", ...]

如何使用 for 循环将我的列表条目插入到负载字典中?

我尝试使用 "regular" 有效负载字典,但没有用:

for url_path in list_of_urls:
    payload = {'url' : url_path,'accuracy_boost':3}

我查看了 API 文档,发现您需要将负载作为 JSON 发送。这样的事情就可以完成工作:

import requests
import json

endpoints = {
    'face': 'https://face-detection6.p.rapidapi.com/img/face'
    'face_age_gender': 'https://face-detection6.p.rapidapi.com/img/face-age-gender'
}

urls = [
    'https://inferdo.com/img/face-3.jpg'
]

headers = {
    'x-rapidapi-host': 'face-detection6.p.rapidapi.com',
    'x-rapidapi-key': 'YOUR-API-KEY',
    'content-type': 'application/json',
    'accept': 'application/json'
}

for url in urls:
    payload = {
        'url': url,
        'accuracy_boost': 3
    }

    r = requests.post(
        endpoints.get('face'), # or endpoint.get('face_age_gender')
        data=json.dumps(payload),
        headers=headers
    )

    if r.ok:
        # do something with r.content or r.json()

希望对您有所帮助。