logo科技微讯

如何使用 GitHub 的 API

作者:科技微讯
日期:2022-05-03
📝 笔记

验证

Github 的 API 有 rate limit,如果直接用浏览器访问 API,rate limit 很低。通常来说使用 GitHub 的 API 时应该附上验证信息,即 authentication。

未验证的 rate limit 是 60 次/小时:

For unauthenticated requests, the rate limit allows for up to 60 requests per hour. Unauthenticated requests are associated with the originating IP address, and not the person making requests. 出处

已验证的是 5000 次/小时,如果验证用户是 GitHub Enterprise Cloud organization,则 rate limit 是 15000/小时。建议的验证方法是 OAuth,用户的 personal access token 就属于 OAuth token:

We recommend you use OAuth tokens to authenticate to the GitHub API. OAuth tokens include personal access tokens and enable the user to revoke access at any time.

请求 API 后,从 response 的 headers 可以获得 rate limit 相关的数据:包括总限额、已用额度、剩余额度。

请求

GitHub 建议把 AOuth token 添加到 header 发送:

GitHub recommends sending OAuth tokens using the Authorization header. 出处

GitHub 的 latest release 不是根据发布时间决定的,好像是根据这个 release 对应的 commit 决定的,同一个 commit 发布多个 release,用 releases/latest 拿到的 release 不一定是最新发布的那个 release,因为 commit 不变。

另外 latest release 这个不返回 pre-release 的数据,如果要获得 pre-release 的信息,应该使用:

const api = `https://api.github.com/repos/${repo}/releases?per_page=5`;

若干 API 例子

第三方库

可以考虑使用 octokit/rest 这个第三方库来操作 GitHub 的 API,它的文档支持搜索你需要的 API 并查看它的用法。

例子:

const { Octokit } = require("@octokit/rest");
const octokit = new Octokit();
octokit.rest.repos
  .listReleases({
    owner: "sindresorhus",
    repo: "got",
  })
  .then((res) => {
    console.log(res);
  });
donation赞赏
thumbsup0
thumbsdown0
暂无评论