GitHub API - Get the number of branches of a repo without listing all its branches
There's no such attribute currently.
However, there's a neat trick you can use to avoid fetching all pages. If you set per_page
to 1
, then each page will contain 1 item and the number of pages (revealed by the last page) will also tell you the total number of items:
https://developer.github.com/v3/#pagination
So, with just one request -- you can get the total number of branches. For example, if you fetch this URL and inspect the Link header:
https://api.github.com/repos/github/linguist/branches?per_page=1
then you'll notice that the Link
header is:
Link: <https://api.github.com/repositories/1725199/branches?per_page=1&page=2>; rel="next", <https://api.github.com/repositories/1725199/branches?per_page=1&page=28>; rel="last"
This tells you that there are 28 pages of results, and because there is one item per page -- the total number of branches is 28.
Hope this helps.
You can also use GraphQL API v4 to get branch count easily :
{
repository(owner: "google", name: "gson") {
refs(first: 0, refPrefix: "refs/heads/") {
totalCount
}
}
}
Try it in the explorer
which gives :
{
"data": {
"repository": {
"refs": {
"totalCount": 13
}
}
}
}
As you are doing this on multiple repo, it's also more straightforward with GraphQL as you can build the query with different aliases per repo & use only one request to get branch count for all of these :
{
fetch: repository(owner: "github", name: "fetch") {
...RepoFragment
}
hub: repository(owner: "github", name: "hub") {
...RepoFragment
}
scientist: repository(owner: "github", name: "scientist") {
...RepoFragment
}
}
fragment RepoFragment on Repository {
refs(first: 0, refPrefix: "refs/heads/") {
totalCount
}
}
Try it in the explorer