我正在尝试使用“params”关键字向GitHub API发出请求:
import requests
parameters = {'language': 'python', 'sort': 'stars'}
url = 'https://api.github.com/search/repositories' #?language:python&sort=stars
response = requests.get(url, params=parameters)
print(response.url)
response_dict = response.json()
items_list = response_dict['items']
for item in items_list:
print(item['name'])
我收到以下错误:
Traceback (most recent call last):
File "github.py", line 10, in <module>
items_list = response_dict['items']
KeyError: 'items'
但是,如果我跳过params方法并将整个URL分配给变量,那么相同的代码工作正常。通过打印两个方法的URL,我注意到使用“params”省略了URL中的“q =”部分。可能是错误的原因,如果是这样,我该如何解决?
有关Search API
的文档声明,您可以在查询字符串参数language
中指定包含由:
分隔的q
的字段,如下所示:
import requests
parameters = {"q": "language:python", "sort": "stars"}
url = "https://api.github.com/search/repositories"
response = requests.get(url, params=parameters)
response.raise_for_status()
response_dict = response.json()
for item in response_dict["items"]:
print(item["name"])
你可以查看documentation,了解你可以添加到q
的其他内容。