GitHub的API接口使用

Keywords: #技术 #GitHub #API
Release Date: 2025-06-04
Table of Contents

GitHub的API接口使用,通过 API 接口完成 GitHub 的各种操作,官方文档

使用 GitHub 的 API 接口需要用到 OAuth2 token,这可以在 Settings/Developer Settings 的 Personal Access Tokens (Classic) 中获取。

以下所有 API 请求,如果是私有仓库或者修改仓库文件内容,都需要在请求头中带上自己的 TOKEN 信息进行身份验证,如 Authorization: Bearer <YOUR-TOKEN>。如果是公开仓库和公共资源,则不需要带上 TOKEN。

获取所有 API

  • 方法:GET

  • 地址:https://api.github.com

  • 返回:所有 API 信息和地址

image.png

获取公开仓库信息

  • 方法:GET

  • 地址:https://api.github.com/repos/{owner}/{repo}

    • {owner} 为仓库拥有者
    • {repo} 为仓库名称
  • 返回:仓库详细信息

image.png

获取仓库文件信息

  • 方法:GET

  • 地址:https://api.github.com/repos/{owner}/{repo}/contents/{path}

    • {path} 为仓库路径
  • 请求头:

    • Accept: application/vnd.github+json
    • Authorization: Bearer <YOUR-TOKEN>
  • 返回:仓库路径中文件的详细信息

image.png

创建更新仓库

  • 方法:PATCH
  • 地址:https://api.github.com/repos/{owner}/{repo}
  • 请求头:
    • Accept: application/vnd.github+json
    • Authorization: Bearer <YOUR-TOKEN>
  • 请求体:
{
    "name": "仓库名称",
    "description": "仓库描述",
    "private": "true",
    ...
}
  • 返回:仓库信息

具体可用的请求体参数见 GitHub 文档

删除仓库

  • 方法:DELETE

  • 地址:https://api.github.com/repos/{owner}/{repo}

  • 请求头:

    • Accept: application/vnd.github+json
    • Authorization: Bearer <YOUR-TOKEN>
  • 返回状态码:

    • 204:无内容(成功)
    • 307:临时重定向
    • 403:组织阻止成员删除仓库
    • 404:资源未找到
    • 409:冲突 `

创建更新文件

  • 方法:PUT
  • 地址:https://api.github.com/repos/{owner}/{repo}/contents/{path}
    • {path} 为仓库路径
  • 请求头:
    • Accept: application/vnd.github+json
    • Authorization: Bearer <YOUR-TOKEN>
  • 请求体:
{
    "message":"提交信息",
    "content":"文件的Base64编码值",
    "sha": "文件的blob SHA值"
    ...
}

更新文件时需要加上 sha 参数,创建文件没有要求。

  • 返回:文件详细信息

具体可用的请求体参数见 GitHub 文档

删除文件

  • 方法:delete
  • 地址:https://api.github.com/repos/{owner}/{repo}/contents/{path}
  • 请求头:
    • Accept: application/vnd.github+json
    • Authorization: Bearer <YOUR-TOKEN>
  • 请求体:
{
    "message":"提交信息",
    "sha":"文件的blob SHA值"
    ...
}
  • 返回:提交详细信息

具体可用的请求体参数见 GitHub 文档

获取仓库的 readme 文件

  • 方法:delete

  • 地址(根目录):https://api.github.com/repos/{owner}/{repo}/readme

  • 地址(子目录):https://api.github.com/repos/{owner}/{repo}/readme/{dir}

  • 请求头:

    • Accept: application/vnd.github+json
    • Authorization: Bearer <YOUR-TOKEN>
  • 返回: readme文件内容和详细信息

image.png

下载仓库归档文件

  • 方法:GET

  • 地址(zip):https://api.github.com/repos/{owner}/{repo}/zipball/{ref}

  • 地址(tar):https://api.github.com/repos/{owner}/{repo}/tarball/{ref}

    • {ref} 为指定分支,如果不填则默认 main 分支
  • 请求头:

    • Accept: application/vnd.github+json
    • Authorization: Bearer <YOUR-TOKEN>
  • 返回:重定向到下载地址

其他 API

以上只是列举了一些常用的 API,详细内容见 GitHub REST API 快速入门 - GitHub 文档