2024-04-15
温故知新
00

目录

前言
通过响应头获取
赞助请求V3

前言

Github 官方提供了很多 API ,可以用于获取很多 Github 上公开的用户和仓库信息。

这是官方文档:GitHub REST API documentation - GitHub Docs

其中有根据用户名获取用户详细信息的接口,可以拿到指定用户的FollowerFollowingPublicRepos等等的数量,但奇怪的是,拿不到该用户的 Starred 仓库数量。

如下是获取用户信息接口的响应数据示例:

json
{ "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/error/octocat_happy.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false, "name": "monalisa octocat", "company": "GitHub", "blog": "https://github.com/blog", "location": "San Francisco", "email": "octocat@github.com", "hireable": false, "bio": "There once was...", "twitter_username": "monatheoctocat", "public_repos": 2, "public_gists": 1, "followers": 20, "following": 0, "created_at": "2008-01-14T04:33:35Z", "updated_at": "2008-01-14T04:33:35Z" }

当然想要获取也有别的方法,如通过 Starred 的仓库列表接口汇总,最后得出一个总数,那就是该用户的总 Starred 数量,但是这样有一个问题,那就是不确定要调用多少次接口。由于Github的分页接口最大单页数量是100,所以才用此方法,Starred的仓库越多,相应需要调用接口的次数越多。

有没有只需要调用一次接口就可以拿到 Starred 数量的方法呢?有大佬找到了方法!

通过响应头获取

本方法参考:stackoverflow 的这个问题反馈,有用户给出解决方案,那就是通过 Starred 列表接口的响应头获取总数,只需调用一次该列表接口就可以拿到!

接口文档:list-repositories-starred-by-a-user

如调用接口:

bash
# 该接口用于获取用户 dingdangdog 的 starred 仓库列表 https://api.github.com/users/dingdangdog/starred

当调用该接口不传参数时,默认查询第一页,且每页默认时 30 条数据。

观察其响应头,它会返回一个名为 Link 的头部信息,内容大概为:

bash
<https://api.github.com/user/45959431/starred?page=2>; rel="next", <https://api.github.com/user/45959431/starred?page=7>; rel="last"

根据这个头部信息猜测,他的最后一页时 7,上面提到,每页默认是 30 条数据,所以大致可猜测出来该用户的总Starred数量。

进一步做些修改:指定每页一条数据!!! 如:

bash
# 指定每页数量为1 https://api.github.com/users/dingdangdog/starred?per_page=1

此时请求该接口的响应头信息会变为:

bash
<https://api.github.com/user/45959431/starred?per_page=1&page=2>; rel="next", <https://api.github.com/user/45959431/starred?per_page=1&page=194>; rel="last"

解析该请求头,得到该用户的总 Starred 仓库数量时 194

PS:194 是截至本文编写时的数量,后续肯定后有所变化!

赞助请求V3

建站因为热爱,生活需要Money,请屏幕前的大佬动动您发财的小手,点击一次以示鼓励,祝您生活愉快!

PS:就目前的访问量,即便每个访客都点一次广告,收入也不足以支付运营成本。如果看不到广告,可能是网络原因或被拦截了,那就算了吧。再次祝您生活愉快~~

如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:DingDangDog

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!