161

We need to display all the projects of a person in his repository on GitHub account.

How can I display the names of all the git repositories of a particular person using his git-user name?

25 Answers 25

122

You can use the github api for this. Hitting https://api.github.com/users/USERNAME/repos will list public repositories for the user USERNAME.

3
48

Use the Github API:

/users/:user/repos

This will give you all the user's public repositories. If you need to find out private repositories you will need to authenticate as the particular user. You can then use the REST call:

/user/repos

to find all the user's repos.

To do this in Python do something like:

USER='AUSER'
API_TOKEN='ATOKEN'
GIT_API_URL='https://api.github.com'

def get_api(url):
    try:
        request = urllib2.Request(GIT_API_URL + url)
        base64string = base64.encodestring('%s/token:%s' % (USER, API_TOKEN)).replace('\n', '')
        request.add_header("Authorization", "Basic %s" % base64string)
        result = urllib2.urlopen(request)
        result.close()
    except:
        print 'Failed to get api request from %s' % url

Where the url passed in to the function is the REST url as in the examples above. If you don't need to authenticate then simply modify the method to remove adding the Authorization header. You can then get any public api url using a simple GET request.

1
  • 41
    This will only give the first "page" of the result set, which is set at 30 items by default. You can use ?per_page=100 to get the maximum ammount but if a user has more than a hundred repos you will need to follow several next URLs in the HTTP Link header send with the response.
    – Potherca
    Commented May 22, 2014 at 20:09
45

Try the following curl command to list the repositories:

GHUSER=CHANGEME; curl "https://api.github.com/users/$GHUSER/repos?per_page=100" | grep -o 'git@[^"]*'

To list cloned URLs, run:

GHUSER=CHANGEME; curl -s "https://api.github.com/users/$GHUSER/repos?per_page=1000" | grep -w clone_url | grep -o '[^"]\+://.\+.git'

If it's private, you need to add your API key (access_token=GITHUB_API_TOKEN), for example:

curl "https://api.github.com/users/$GHUSER/repos?access_token=$GITHUB_API_TOKEN" | grep -w clone_url

If the user is organisation, use /orgs/:username/repos instead, to return all repositories.

To clone them, see: How to clone all repos at once from GitHub?

See also: How to download GitHub Release from private repo using command line

11
  • 11
    This shows only the first 100 repositories, regardless of the per_page=1000.
    – clt60
    Commented Aug 12, 2016 at 7:07
  • 3
    Add the -s option to your curl command to get rid of those unsightly progress bars, as in curl -s ...
    – xmnboy
    Commented Mar 11, 2017 at 1:41
  • 7
    As @jm666 says, the maximum page size is 100. To see the 2nd page, do: curl "api.github.com/users/$USER/repos?per_page=100\&page=2"
    – rscohn2
    Commented Dec 4, 2017 at 1:17
  • 4
    The private example won't work with the example, /users/ "in plural" only returns public repos. You need to go with api.github.com/user/repos and add the token into the request to get private ones.
    – lrepolho
    Commented Feb 4, 2019 at 23:24
  • 3
    @kenorb mystery solved, the user is an org so /orgs/:username/repos return all the repos, /users/... return part of them, this is indeed weird. the username can be treated as both an user or an org. Commented Mar 2, 2019 at 1:31
21

Using the gh command

You can use the github cli for this:

gh api users/:owner/repos

or

gh api orgs/:orgname/repos

For all the repos you'll want --paginate and you can combine this with --jq to show only name for each repo:

gh api orgs/:orgname/repos --paginate  --jq '.[].name' | sort
15

Here is a full spec for the repos API:

https://developer.github.com/v3/repos/#list-repositories-for-a-user

GET /users/:username/repos

Query String Parameters:

The first 5 are documented in the API link above. The parameters for page and per_page are documented elsewhere and are useful in a full description.

  • type (string): Can be one of all, owner, member. Default: owner
  • sort (string): Can be one of created, updated, pushed, full_name. Default: full_name
  • direction (string): Can be one of asc or desc. Default: asc when using full_name, otherwise desc
  • page (integer): Current page
  • per_page (integer): number of records per page

Since this is an HTTP GET API, in addition to cURL, you can try this out simply in the browser. For example:

https://api.github.com/users/grokify/repos?per_page=2&page=2

1
12

If you have jq installed, you can use the following command to list all public repos of a user

curl -s https://api.github.com/users/<username>/repos | jq '.[]|.html_url'
0
8

You probably need a jsonp solution:

https://api.github.com/users/[user name]/repos?callback=abc

If you use jQuery:

$.ajax({
  url: "https://api.github.com/users/blackmiaool/repos",
  jsonp: true,
  method: "GET",
  dataType: "json",
  success: function(res) {
    console.log(res)
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

7

The NPM module repos grabs the JSON for all public repos for some user or group. You can run this directly from npx so you don't need to install anything just pick an org or user ("W3C" here):

$ npx repos W3C W3Crepos.json

This will create a file called W3Crepos.json. Grep is good enough to e.g. fetch the list of repos:

$ grep full_name W3Crepos.json

pros:

  • Works with more than 100 repos (many answers to this question don't).
  • Not much to type.

cons:

  • Requires npx (or npm if you want to install it for real).
6

There's now an option to use the awesome GraphQL API Explorer.

I wanted a list of all my org's active repos with their respective languages. This query does just that:

{
  organization(login: "ORG_NAME") {
    repositories(isFork: false, first: 100, orderBy: {field: UPDATED_AT, direction: DESC}) {
      pageInfo {
        endCursor
      }
      nodes {
        name
        updatedAt
        languages(first: 5, orderBy: {field: SIZE, direction: DESC}) {
          nodes {
            name
          }
        }
        primaryLanguage {
          name
        }
      }
    }
  }
}

5

Retrieve the list of all public repositories of a GitHub user using Python:

import requests
username = input("Enter the github username:")
request = requests.get('https://api.github.com/users/'+username+'/repos')
json = request.json()
for i in range(0,len(json)):
  print("Project Number:",i+1)
  print("Project Name:",json[i]['name'])
  print("Project URL:",json[i]['svn_url'],"\n")

Reference

2
  • 2
    this not working (maybe it's for older api version)
    – OzzyCzech
    Commented Feb 12, 2020 at 7:44
  • 4
    yes, there is a small change. I have edited my answer, and now it works well.
    – darshanc99
    Commented Feb 13, 2020 at 16:56
5

If looking for repos of an organisation-

api.github.com/orgs/$NAMEOFORG/repos

Example:

curl https://api.github.com/orgs/arduino-libraries/repos

Also you can add the per_page parameter to get all names just in case there is a pagination problem-

curl https://api.github.com/orgs/arduino-libraries/repos?per_page=100
3

Using Python

import requests

link = ('https://api.github.com/users/{USERNAME}/repos')

api_link = requests.get(link)
api_data = api_link.json()

repos_Data = (api_data)

repos = []

[print(f"- {items['name']}") for items in repos_Data]

If you want to get all the repositories in a list (array) you could do something like this:

import requests

link = ('https://api.github.com/users/{USERNAME}/repos')

api_link = requests.get(link)
api_data = api_link.json()

repos_Data = (api_data)

repos = []

[repos.append(items['name']) for items in repos_Data]

This will store all the repositories in the "repos" array.

2

HTML

<div class="repositories"></div>

JavaScript

// Github repos

If you wanted to limit the repositories list, you can just add ?per_page=3 after username/repos.

e.g username/repos?per_page=3

Instead of /username/, you can put any person's username on Github.

var request = new XMLHttpRequest();
        request.open('GET','https://api.github.com/users/username/repos' , 
        true)
        request.onload = function() {
            var data = JSON.parse(this.response);
            console.log(data);
            var statusHTML = '';
            $.each(data, function(i, status){
                statusHTML += '<div class="card"> \
                <a href=""> \
                    <h4>' + status.name +  '</h4> \
                    <div class="state"> \
                        <span class="mr-4"><i class="fa fa-star mr-2"></i>' + status.stargazers_count +  '</span> \
                        <span class="mr-4"><i class="fa fa-code-fork mr-2"></i>' + status.forks_count + '</span> \
                    </div> \
                </a> \
            </div>';
            });
            $('.repositories').html(statusHTML);
        }
        request.send();
2

Paging JSON

The JS code below is meant to be used in a console.

username = "mathieucaroff";
    
Promise.all(Array.from({ length: Math.ceil(1+184/30) }, (_, p) =>
    fetch(`//api.github.com/users/${username}/repos?page=${p}`).then(r => r.json())
)).then(all => {
    window.jo = [].concat(...all);
    // window.jof = window.jo.map(x => x.forks);
    // window.jow = window.jo.map(x => x.watchers);
    return window.jo
})
1

The answer is "/users/:user/repo", but I have all the code that does this in an open-source project that you can use to stand up a web-application on a server.

I stood up a GitHub project called Git-Captain that communicates with the GitHub API that lists all the repos.

It's an open-source web-application built with Node.js utilizing GitHub API to find, create, and delete a branch throughout numerous GitHub repositories.

It can be setup for organizations or a single user.

I have a step-by-step how to set it up as well in the read-me.

1

To get the user's 100 public repositories's url:

$.getJSON("https://api.github.com/users/suhailvs/repos?per_page=100", function(json) {
  var resp = '';
  $.each(json, function(index, value) {
    resp=resp+index + ' ' + value['html_url']+ ' -';
    console.log(resp);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

1
const request = require('request');
const config = require('config');

router.get('/github/:username', (req, res) => {
    try {
        const options = {

            uri: `https://api.github.com/users/${req.params.username}/repos?per_page=5
                 &sort=created:asc
                 &client_id=${config.get('githubClientId')}
                 &client_secret=${config.get('githubSecret')}`,

            method: 'GET',

            headers: { 'user-agent': 'node.js' }
        };
        request(options, (error, response, body) => {
            if (error) console.log(error);
            if (response.statusCode !== 200) {
                res.status(404).json({ msg: 'No Github profile found.' })
            }
            res.json(JSON.parse(body));
        })
    } catch (err) {
        console.log(err.message);
        res.status(500).send('Server Error!');
    }
});
2
  • 1
    for more details visit git docs-> developer.github.com/v3/repos Commented Nov 26, 2019 at 12:28
  • 1
    Welcome to SO! Please check this before posting... When you post an answer and there are some more, show the Pros of your POV and, please, don´t just post code, explain it a little bit. Commented Nov 26, 2019 at 12:50
1

Using Javascript Fetch

async function getUserRepos(username) {
   const repos = await fetch(`https://api.github.com/users/${username}/repos`);
   return repos;
}

getUserRepos("[USERNAME]")
      .then(repos => {
           console.log(repos);
 }); 
1

Slightly improved version of @joelazar's answer to get as a cleaned list:

gh repo list <owner> -L 400 |awk '{print $1}' |sed "s/<owner>\///"

Replace with the owner name, of course.

This can get lists with >100 repos as well (in this case, 400)

1

Paging Bash

Paste your token in a file called github_token_file and give it permissions 0400.

GITHUB_TOKEN=$(cat github_token_file)
USER=myuser

page=1
while : ; do
    echo Page $page
    result=$(curl --header "authorization: Bearer $GITHUB_TOKEN" "https://api.github.com/user/repos?per_page=100&page=$page")
    echo $result | jq '.[].name' | sort
    wc=$(echo $result | wc -w)
    [[ $wc -lt "10" ]] && break || true
    page=$((page+1))
done

Note that by using /users/<username>/repos you are hitting the public repos only, while /user/repos is hitting both public and private.

0

Using the official GitHub command-line tool:

gh auth login

gh api graphql --paginate -f query='
query($endCursor: String) {
    viewer {
    repositories(first: 100, after: $endCursor) {
        nodes { nameWithOwner }
        pageInfo {
        hasNextPage
        endCursor
        }
    }
    }
}
' | jq ".[] | .viewer | .repositories | .nodes | .[] | .nameWithOwner"

Note: this will include all of your public, private and other people's repos that are shared with you.

References:

0

And in case you want to list repo names filtered by specific topic:

gh search repos --owner=<org> --topic=payments --json name --jq ".[].name" --limit 200
0

A bit more memorable (simplified) versions of this answer (upvoted) to get public repos (only):

# quick way to get all (up to 100) public repos for user mirekphd
$ curl -s "https://api.github.com/users/mirekphd/repos?per_page=100" | grep full_name | sort

The current method to get all (up to 100) private repos from Github API (see docs and this answer):

# get all private repos from the Github API 
# after logging with Personal Access Token (assuming secure 2FA is used)
$ export GITHUB_USER=mirekphd && export GITHUB_TOKEN=$(cat <path_redacted>/personal-github-token) && curl -s --header "Authorization: Bearer $GITHUB_TOKEN" --request GET "https://api.github.com/search/repositories?q=user:$GITHUB_USER&per_page=100" | grep "full_name" | sort
0

Just do it in postman. This way you can visualize it, run scripts, etc.

Check it out.

https://learning.postman.com/docs/sending-requests/visualizer/

enter image description here

enter image description here

0

For those on Windows here is a Powershell approach. You must install the GitHub CLI as documented above.

function git-clone-all ([string] $username,[System.IO.FileInfo] $dir, $repos) {
    if (-Not (Test-Path -PathType Container -Path $dir)) {New-Item -ItemType Directory -Force $dir | Out-Null}
    if (-Not $repos) {$repos=$(gh api https://api.github.com/users/$username/repos --paginate  --jq '.[].name' | sort)}
    foreach ($repo in $repos) {git clone https://github.com/$username/$repo "$dir\$repo"}
}

If you don't want to clone all repositories one approach is:

gh api https://api.github.com/users/$username/repos --paginate  --jq '.[].name' | sort | Out-File "somefile.txt"

edit "somefile.txt", and call the function as:

git-clone-all "username" "dir" $(gc "somefile.txt")

I'm sure it can be improved with additional gh command line switches. I haven't tested this with >100 repositories for a user.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.