python request.get API参数、标头、参数

2024-10-03 06:19:14 发布

您现在位置:Python中文网/ 问答频道 /正文

对于API的Python请求,我对URL参数、参数和request.get()参数感到困惑,即使在阅读了Python和API文档之后也是如此。我只想得到那只叫“名字”的狗:“秋田”

以下代码适用于5条记录的限制,但返回的记录是随机的,而不仅仅是“Akita”(我知道它存在)。我尝试了许多引号、大括号、字典格式、预写字符串等的排列。所有这些都返回无记录、所有记录或语法失败

response_dog = requests.get("https://api.thedogapi.com/v1/images/search?limit=5", params={'name': 'Akita'})
for current_dog in response_dog.json():
    print("\n",current_dog)

输出5只随机狗;想要的只是一只名为“秋田”的狗


Tags: 代码文档apiurl参数getresponserequest
1条回答
网友
1楼 · 发布于 2024-10-03 06:19:14

如果您需要特定犬种的信息,为什么要使用为随机犬生成信息的API端点

我想你要找的是: https://docs.thedogapi.com/api-reference/breeds/breeds-search#send-a-test-request

文档告诉您如何制定请求,包括标题、查询字符串参数和端点URL:

import requests

url = "https://api.thedogapi.com/v1/breeds/search"

params = {
    "q": "akita"
}

headers = {
    "x-api-key": "YOUR_API_KEY"
}

response = requests.get(url, params=params, headers=headers)
response.raise_for_status()

print(response.json()[0]["temperament"])

注意:我没有测试过这个,因为我没有API密钥,但是根据文档,它应该可以工作

相关问题 更多 >