如何提升GitHub用户信息查询API的调用速率限制?
GitHub API 限流提升方案
你当前遇到的是GitHub未认证请求的默认限流限制,未认证请求每小时仅允许60次,可通过以下方案解决:
- 方案1:使用个人访问令牌(PAT)认证,认证后请求限流可提升至每小时5000次
操作步骤:- 登录GitHub,进入设置-开发者设置-Personal access tokens,生成仅授予用户信息读取权限的PAT
- 在请求头中添加
Authorization字段,值为token 你的PAT值
注意:PAT属于敏感凭据,禁止直接硬编码在前端公开代码中,前端场景需将API请求转发至自有后端,由后端携带PAT发起GitHub请求
- 方案2:添加本地缓存减少重复请求
GitHub公开用户信息更新频率极低,你可以将请求成功的用户数据按githubIdOrLogin为Key缓存,缓存有效期可设置为1~24小时,相同用户的重复请求直接返回缓存数据,无需调用GitHub接口 - 方案3:规模化使用场景选择GitHub App认证
如果你的服务请求量超过每小时5000次,可以创建GitHub App,通过安装凭证发起请求,限流额度可根据安装量进一步提升,最高可到每小时15000次/安装实例
代码修改示例(后端环境使用,仅作参考)
// 建议将PAT存入环境变量,不要直接写在代码中 const GITHUB_PAT = process.env.GITHUB_PAT; export const getGitHubUserData = async (githubIdOrLogin) => { return fetch(`https://api.github.com/user/${githubIdOrLogin}`, { headers: { Accept: "application/json", ...(GITHUB_PAT && { Authorization: `token ${GITHUB_PAT}` }) }, }).then((res) => { if (!res.ok) { const err = new Error() err.response = res if (res.status === 403 && res.headers.get("X-RateLimit-Remaining") === "0") { const resetsAtMS = Number(`${res.headers.get("X-RateLimit-Reset")}000`) err.message = `Rate limit exceeded, try again in ${Math.ceil( (resetsAtMS - Date.now()) / 60000 )}m` err.code = "github/rate-limit-exceeded" err.resetsAt = resetsAtMS } else if (res.status === 404) { err.message = `Could not find user data for github:${githubIdOrLogin}` err.code = "github/not-found" } else { err.message = `Unexpected status code: ${res.status}` err.code = "github/unknown" } return Promise.reject(err) } return res.json() }) }
内容的提问来源于stack exchange,提问作者r121
相关产品推荐
相关产品推荐

