Search code examples
github-api

Get user total starred count using Github API v3


From the doc, I can list repositories being starred using:

GET /users/:username/starred

But it seems that I can't directly get the count of total starred repos of a user.

Am I missing something?


Solution

  • This is a very interesting question, and I think I have found the answer to it. Let us use the GitHub top user chart to randomly choose Ocramius with their 299 starred repos, available in JSON form from this address.

    Now let us try querying the headers through curl -I "https://api.github.com/users/Ocramius/starred". We get one hopeful-looking header:

    Link: https://api.github.com/user/154256/starred?page=2; rel="next", https://api.github.com/user/154256/starred?page=10; rel="last"

    This header comes from the pagination feature of the API, so what happens if we ask for one record per page with curl -I "https://api.github.com/users/Ocramius/starred?per_page=1"?

    Link: https://api.github.com/user/154256/starred?per_page=1&page=2; rel="next", https://api.github.com/user/154256/starred?per_page=1&page=299; rel="last"

    Aha! If we parse this RFC5988 HTTP header, we can strip out the page number tagged as rel="last" and we have the correct answer of 299!