如何在Python中使用GitHub API

1,094 阅读6分钟

在Python中使用GitHub API

当从网络上获取信息时,我们通常要求获取完整的网页,并通过解析HTML脚本来提取信息。同样地,应用编程接口(API)以更有效的方式执行同样的操作。

本教程将教你如何创建一个独立的应用程序,根据它通过API获得的信息生成一个摘要。

[GitHub]是一个网站,程序员可以在这里为各种开源项目作出贡献。

在这篇文章中,我们将使用[Github API]请求与 GitHub 上的 Python 项目有关的信息。我们还将总结一下我们通过API获得的信息。

前提条件

作为先决条件,你必须对Python有一点了解,才能跟着教程走。

目标

在这篇文章中,我们将经历。

  • 使用API调用来请求数据。
  • 安装requests 库。
  • 跟踪 API 响应。
  • 使用响应字典。
  • 总结顶级存储库。

使用API调用请求数据

GitHub 的网络 API 允许你对一系列数据进行 API 请求。

在网页浏览器的URL栏中输入以下内容,然后按回车键,看看API调用的样子。

https://api.github.com/search/repositories?q=language:python&sort=stars

让我们来看看API调用的各个部分。

  • https://api.github.com/ - 将请求发送到处理API调用的GitHub网络服务器。
  • search/repositories - 是通知 API 在所有 GitHub 仓库中进行搜索的端点。
  • ? - 表示要传递一个参数。
  • q=- 字符q 代表query
  • language:python - 查询只使用Python作为主语言的仓库。
  • &sort=stars - 项目按其获得的星星数量排序。

在获取API数据后,响应会看起来像。

{
  "total_count": 7668509,
  "incomplete_results": false,
  "items": [
    {
      "id": 54346799,
      "node_id": "MDEwOlJlcG9zaXRvcnk1NDM0Njc5OQ==",
      "name": "public-apis",
      "full_name": "public-apis/public-apis",
      --snip--

注意:上面的输出只显示了响应的前几行。

让我们检查一下输出。

  • 在结果的第二行,你可以看到GitHub总共检测到了7668509 Python项目。
  • 如果incomplete results 的值是false ,我们就知道请求成功了。
  • 键值items 保存了一个对象列表,其中包含了GitHub上基于Python的项目信息。

让我们尝试通过使用Python解析API的输出来探索更多信息。

安装请求

requests 包使我们能够从网站上请求数据,并使用 Python 程序轻松评估结果。

运行下面的命令来安装requests

pip install --user requests

处理一个API响应

为了获取GitHub上最受欢迎的Python项目,我们将开始编写一个程序,进行API调用并评估数据,如图所示。

import requests

# Create an API request 
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
response = requests.get(url)
print("Status code: ", response.status_code)
# In a variable, save the API response.
response_dict = response.json()
# Evaluate the results.
print(response_dict.keys())

让我们来理解上面的代码片段。

  • 我们首先导入requests 模块。
  • 然后,我们使用requests 包,用get() 对特定的url 进行API调用。
  • API响应被一个名为response 的变量所保存。
  • response 对象的status_code 属性表明请求是否完成。
  • 一个成功的API调用返回status_code 200 ,而一个不成功的调用返回500
  • 然后,我们使用json() 函数将信息从JSON格式转换为Python字典。
  • 我们将转换后的JSON存储在response_dict

然后,我们打印来自response_dict 的键,如下所示。

Status code: 200
dict_keys(['items', 'total_count', 'incomplete_results'])

使用响应字典

现在,让我们做一个报告,把所有的信息汇总起来。

在这里,我们将计算可用资源库的总数,语言为Python ,并获取items 下的所有键,如图所示。

print("Total repos:", response_dict['total_count'])
# find total number of repositories
repos_dicts = response_dict['items']
print("Repos found:", len(repos_dicts))
# examine the first repository
repo_dict = repos_dicts[0]
print("Keys:", len(repo_dict))
for key in sorted(repo_dict.keys()):
 print(key)

让我们来理解上面的代码片断。

  • total_count 链接的值反映了可用的 GitHub Python 项目的数量。
  • items 的值是一个字典列表,每个字典都提供了关于单个 Python 仓库的信息。
  • 然后,字典的列表被保存在repos_dicts
  • 我们从repos_dicts 中选择第一项,以更仔细地查看关于每个资源库的信息。
  • 最后,我们打印一个item 的所有键。

输出。

Status code: 200
Total repos: 7694326
Repos found: 30
Keys: 74
archive_url
archived
assignees_url
--snip--

url
watchers
watchers_count

GitHub API 会为每个仓库取回一系列数据,比如。

  • status_code 如 。200
  • 仓库的总数,如7694326
  • 找到的仓库总数为30
  • 每个仓库repo_dict74 键。

你可以通过观察这些键来了解你能得到的版本库信息的类型。

让我们看看 repos dict 中的一些键的含义。

# Find out more about the repositories.
repos_dicts = response_dict['items']
print("Repositories found:", len(repos_dicts))
# Examine the first repository.
repo_dict = repos_dicts[0]
print("\nThe following is some information regarding the first repository:")
print('Name:', repo_dict['name'])  #print the project's name
print('Owner:', repo_dict['owner']['login'])  #use the key owner and the the key login to get the dictionary describing the owner and the owner’s login name respectively.
print('Stars:', repo_dict['stargazers_count'])  #print how many stars the project has earned
print('Repository:', repo_dict['html_url'])  #print URL for the project’s GitHub repoitory
print('Created:', repo_dict['created_at'])  #print when it was created
print('Updated:', repo_dict['updated_at'])  #show when it was last updated
print('Description:', repo_dict['description']) #print the repository’s description

输出。

Status-code: 200
Total repos: 7588335
Repositories found: 30

The following is some information regarding the first repository:
Name: public-apis
Owner: public-apis
Stars: 144904
Repository: https://github.com/public-apis/public-apis
Created: 2016-03-20T23:49:42Z
Updated: 2021-07-31T13:15:51Z
Description: A collective list of free APIs

检查输出。

  • 你可以看到,GitHub 上最流行的 Python 仓库是public-apis
  • 该仓库的所有者是public-apis
  • 它的星级超过了140,000 次。
  • 项目的创建日期是2016 March
  • public-apis 的项目描述是collective collection of open APIs

总结顶级软件库

我们将尝试分析一个以上的资源库。

让我们创建一个循环,打印由API调用提供的每个存储库的指定信息。

 --snip--
# Find out more about the repositories.
repos_dicts = respons_dict['items']
print("Repositories found:", len(repos_dicts))
print("\nListed details on each repository:")
for repos_dict in repos_dicts:   #loop through all the dictionaries in repos_dicts.
    print('\nName:', repos_dict['name'])
    print('Owner:', repos_dict['owner']['login'])
    print('Stars:', repos_dict['stargazers_count'])
    print('Repository:', repos_dict['html_url'])
    print('Description:', repos_dict['description'])

我们在循环内打印每个项目的名称、所有者、拥有的星数、GitHub URL 以及项目的描述。

Name: public-apis
Owner: public-apis
Stars: 144910
Repository: https://github.com/public-apis/public-apis
Description: A collective list of free APIs

Name: system-design-primer
Owner: donnemartin
Stars: 139818
Repository: https://github.com/donnemartin/system-design-primer
Description: Learn how to design large-scale systems.
--snip--

Name: Python
Owner: TheAlgorithms
Stars: 113616
Repository: https://github.com/TheAlgorithms/Python
Description: All Algorithms implemented in Python

结论

在本教程中,我们已经学习了以下内容。

  • 使用API调用来请求数据。
  • 安装请求。
  • 处理API响应。
  • 使用响应字典。
  • 总结顶级存储库。