来源:《Python编程:从入门到实践》
{
"total_count": 4149745,
"incomplete_results": false,
"items": [
{
"id": 21289110,
"node_id": "MDEwOlJlcG9zaXRvcnkyMTI4OTExMA==",
"name": "awesome-python",
"full_name": "vinta/awesome-python",
--snip--
$ pip install --user requests
python_repos.py
import requests
# 执行API调用并存储响应
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code:", r.status_code)
# 将API响应存储在一个变量中
response_dict = r.json()
# 处理结果
print(response_dict.keys())
模块requests
调用get()并将URL传递给它,再将响应对象存储在变量r中
状态码200表示请求成功
)方法json()将这些信息转换为一个Python字典
存储在response_dict中
python_repos.py
import requests
# 执行API调用并存储响应
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
r = requests.get(url)
print("Status code:", r.status_code)
# 将API响应存储在一个变量中
response_dict = r.json()
print("Total repositories:", response_dict['total_count'])
# 探索有关仓库的信息
repo_dicts = response_dict['items']
print("Repositories returned:", len(repo_dicts))
# 研究第一个仓库
repo_dict = repo_dicts[0]
print("\nKeys:", len(repo_dict))
for key in sorted(repo_dict.keys()):
print(key)
total_count
关联的值,它指出当前GitHub总共包含多少个Python仓库python_repos.py
--snip--
# 探索有关仓库的信息
repo_dicts = response_dict['items']
print("Repositories returned:", len(repo_dicts))
# 研究第一个仓库
repo_dict = repo_dicts[0]
print("\nSelected information about first repository:")
print('Name:', repo_dict['name'])
print('Owner:', repo_dict['owner']['login'])
print('Stars:', repo_dict['stargazers_count'])
print('Repository:', repo_dict['html_url'])
print('Created:', repo_dict['created_at'])
print('Updated:', repo_dict['updated_at'])
print('Description:', repo_dict['description'])
python_repos.py
--snip--
# 探索有关仓库的信息
repo_dicts = response_dict['items']
print("Repositories returned:", len(repo_dicts))
print("\nSelected information about each repository:")
for repo_dict in repo_dicts:
print('\nName:', repo_dict['name'])
print('Owner:', repo_dict['owner']['login'])
print('Stars:', repo_dict['stargazers_count'])
print('Repository:', repo_dict['html_url'])
print('Description:', repo_dict['description'])
{
"resources": {
"core": {
"limit": 60,
"remaining": 60,
"reset": 1566879699
},
"search": {
"limit": 10,
"remaining": 10,
"reset": 1566876159
},
"graphql": {
"limit": 0,
"remaining": 0,
"reset": 1566879699
},
"integration_manifest": {
"limit": 5000,
"remaining": 5000,
"reset": 1566879699
}
},
"rate": {
"limit": 60,
"remaining": 60,
"reset": 1566879699
}
}
注意: 很多API都要求你注册获得API密钥后才能执行API调用