Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get user total starred count using Github API v3

Tags:

github-api

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?

like image 386
skyline75489 Avatar asked Jun 04 '15 06:06

skyline75489


2 Answers

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!

like image 68
Ken Y-N Avatar answered Nov 15 '22 01:11

Ken Y-N


A suggestion to Ken Y-N's answer:

When the user has only one or zero starred count,the api will response without the Link header.

So when response has not the Link header, you can directly to get the starred count from the JSON-ARRAY's length in the response body.It just can be 0 or 1.

like image 45
QuinnChen Avatar answered Nov 14 '22 23:11

QuinnChen