We are working on a project where we need to display all the projects of a person in his repository on GitHub account.
Can anyone suggest, how can I display the names of all the git repositories of a particular person using his git-user name?
You can use the github api for this. Hitting https://api.github.com/users/USERNAME/repos
will list public repositories for the user USERNAME.
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.
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
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'
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 pageper_page
(integer): number of records per pageSince 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
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>
gh
commandYou 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
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:
cons:
npx
(or npm
if you want to install it for real).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")
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
}
}
}
}
}
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
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();
The JS code below is meant to be used in a console.
username = "mathieucaroff";
w = window;
Promise.all(Array.from(Array(Math.ceil(1+184/30)).keys()).map(p =>
fetch(`//api.github.com/users/{username}/repos?page=${p}`).then(r => r.json())
)).then(all => {
w.jo = [].concat(...all);
// w.jo.sort();
// w.jof = w.jo.map(x => x.forks);
// w.jow = w.jo.map(x => x.watchers)
})
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.
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>
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!');
}
});
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: