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

我有一个全部引用图像的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循环将列表的条目插入有效负载字典?

我尝试使用“常规”有效载荷字典,但是没有用:

for url_path in list_of_urls:
    payload = {'url' : url_path,'accuracy_boost':3}
gigajin 回答:为请求API有效负载创建变量字符串

我去了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()

我希望这会有所帮助。

本文链接:https://www.f2er.com/2790963.html

大家都在问