medkhelifi
medkhelifi

Reputation: 1121

How to get the number of forks of a GitHub repo with the GitHub API?

I use Github API V3 to get forks count for a repository, i use:

GET /repos/:owner/:repo/forks

The request bring me only 30 results even if a repository contain more, I googled a little and I found that due to the memory restrict the API return only 30 results per page, and if I want next results I have to specify the number of page.

Only me I don't need all this information, all I need is the number of forks.
Is there any way to get only the number of forks?

Because If I start to loop page per page my script risque to crash if a repository contain thousand results.

Upvotes: 5

Views: 4216

Answers (2)

Artem Smirnov
Artem Smirnov

Reputation: 411

I had a job where I need to get all forks as git-remotes of a github project.

I wrote the simple python script https://gist.github.com/urpylka/9a404991b28aeff006a34fb64da12de4

At the base of the program is recursion function for getting forks of a fork. And I met same problem (GitHub API was returning me only 30 items).

I solved it with add increment of ?page=1 and add check for null response from server.

def get_fork(username, repo, forks, auth=None):

page = 1
while 1:

    r = None
    request = "https://api.github.com/repos/{}/{}/forks?page={}".format(username, repo, page)
    if auth is None: r = requests.get(request)
    else: r = requests.get(request, auth=(auth['login'], auth['secret']))
    j = r.json()
    r.close()

    if 'message' in j:
        print("username: {}, repo: {}".format(username, repo))
        print(j['message'] + " " + j['documentation_url'])
        if str(j['message']) == "Not Found": break
        else: exit(1)

    if len(j) == 0: break
    else: page += 1

    for item in j:
        forks.append({'user': item['owner']['login'], 'repo': item['name']})

        if auth is None:
            get_fork(item['owner']['login'], item['name'], forks)
        else:
            get_fork(item['owner']['login'], item['name'], forks, auth)

Upvotes: 5

VonC
VonC

Reputation: 1323803

You can try and use a search query.

For instance, for my repo VonC/b2d, I would use:

https://api.github.com/search/repositories?q=user%3AVonC+repo%3Ab2d+b2d

The json answer gives me a "forks_count": 5

Here is one with more than 4000 forks (consider only the first result, meaning the one whose "full_name" is actually "strongloop/express")

https://api.github.com/search/repositories?q=user%3Astrongloop+repo%3Aexpress+express

"forks_count": 4114,

Upvotes: 6

Related Questions