python request.get API 参数、标头、参数 - 混淆

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

以下代码适用于 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条随机狗;想要的只是'name'的一只狗:'Akita'

ddyyqqrr 回答:python request.get API 参数、标头、参数 - 混淆

如果您需要特定犬种的信息,为什么要使用生成随机犬信息的 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 密钥,但根据文档它应该可以工作。

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

大家都在问