Skip to content
On this page

Python 调用 GitHub API 示例代码

# Python 调用 GitHub API 示例代码

```python
# 导入requests网络请求库,用来发送HTTP请求
import requests

# 向 GitHub API 发送 GET 请求
# get() 就是HTTP的GET方式,去获取octocat这个github用户的公开信息
response = requests.get ("https://api.github.com/users/octocat")

# 将 JSON 格式的响应数据,转换成Python字典(dict)
# GitHub接口返回的数据是JSON字符串,response.json()自动解析成字典,方便用键取值
data = response.json ()

# 提取字典里面对应key的值并打印输出
print ("用户名:", data ["login"])      # login 对应github用户名 octocat
print ("用户 ID:", data ["id"])        # id 是github分配给该用户的数字ID
print ("仓库地址:", data ["repos_url"]) # repos_url 是获取该用户所有仓库的API接口地址
text
用户名: octocat
用户 ID: 583231
仓库地址: https://api.github.com/users/octocat/repos