This GitHub API page 提供完整参考。读取文件的 API 端点:
https://api.github.com/repos/{username}/{repository_name}/contents/{file_path}
{
"encoding": "base64",
"size": 5362,
"name": "README.md",
"content": "encoded content ...",
"sha": "3d21ec53a331a6f037a91c368710b99387d012c1",
...
}
使用 curl,jq
通过 curl 和 jq 使用 GitHub 的 API 阅读 https://github.com/airbnb/javascript/blob/master/package.json:
curl https://api.github.com/repos/airbnb/javascript/contents/package.json | jq -r ".content" | base64 --decode
使用 Python
在 Python 中使用 GitHub 的 API 阅读 https://github.com/airbnb/javascript/blob/master/package.json:
import base64
import json
import requests
import os
def github_read_file(username, repository_name, file_path, github_token=None):
headers = {}
if github_token:
headers['Authorization'] = f"token {github_token}"
url = f'https://api.github.com/repos/{username}/{repository_name}/contents/{file_path}'
r = requests.get(url, headers=headers)
r.raise_for_status()
data = r.json()
file_content = data['content']
file_content_encoding = data.get('encoding')
if file_content_encoding == 'base64':
file_content = base64.b64decode(file_content).decode()
return file_content
def main():
github_token = os.environ['GITHUB_TOKEN']
username = 'airbnb'
repository_name = 'javascript'
file_path = 'package.json'
file_content = github_read_file(username, repository_name, file_path, github_token=github_token)
data = json.loads(file_content)
print(data['name'])
if __name__ == '__main__':
main()