Search code examples
github-api

GitHub API - Get the number of branches of a repo without listing all its branches


I'm currently writing a small project using the GitHub API v3.

I'm constantly doing a calculation based on the number of branches a repo contains. I can't seem to find a way to do so without also requesting to list all the branches of that repo. The need to request that repo's branches adds unnecessary running time, especially when dealing with hundreds of repos, containing dozens of branches each.

The apparent lack of ability to do so caught me by a small surprise, since a quite similar operation, getting the number of repos of an organization, is easily available by doing so:

  1. Get an organization. e.g. GET https://api.github.com/orgs/cloudify-cosmo, using proper GitHub authentication credentials.
  2. Assuming the authentication was successful, in the response body there are two fields named public_repos and total_private_repos
  3. To get the number of repos, just add the values of these two fields.

So, am I missing something? Is there a similarly-convenient way (or any way at all) of getting the number of branches of a repo without having to list its branches?


Solution

  • 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.