Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 3666

Java API for GitHub using GitHub-API

$
0
0

1. Introduction

In this article, we’re going to have a look at the GitHub API For Java library. This provides us with an object-oriented representation of the GitHib API, allowing us to easily interact with it from our Java applications.

2. Dependencies

To use the GitHub API for Java library, we need to include the latest version in our build, which is currently 1.327.

If we’re using Maven, we can include this dependency in our pom.xml file:

<dependency>
    <groupId>org.kohsuke</groupId>
    <artifactId>github-api</artifactId>
    <version>1.327</version>
</dependency>

At this point, we’re ready to start using it in our application.

3. Client Creation

In order to use the library, we first need to create a GitHub client instance. This acts as the main entrypoint for interacting with the GitHub API.

The easiest way to create this instance is to connect anonymously:

GitHub gitHub = GitHub.connectAnonymously();

This then lets us access the API without any authentication credentials. However, what we can do with this is restricted to only those features that can work in this way.

Alternatively, we can connect with credentials:

GitHub gitHub = GitHub.connect();

Doing this will attempt to determine the credentials to use in several different ways:

  • If the environment property GITHUB_OAUTH is set, then this will be used as a personal access token.
  • Otherwise, if the environment property GITHUB_JWT is set, this will be used as a JWT token.
  • Otherwise, if both GITHUB_LOGIN and GITHUB_PASSWORD are set then these will be used directly as credentials.
  • Otherwise, we’ll attempt to use the .github properties file in the user’s home directory to provide the equivalent properties. In this case, the names will be lowercase and without the GITHUB_ prefix.

If none of these values are available, creating the client will fail.

We can additionally choose to create the client by providing the credentials ourselves manually:

GitHub github = new GitHubBuilder().withOAuthToken("my_personal_token").build();
GitHub github = new GitHubBuilder().withJwtToken("my_jwt_token").build();
GitHub github = new GitHubBuilder().withPassword("my_user", "my_password").build();

If we choose to use one of these, we can then load the appropriate credentials from wherever we wish.

Also, note that the library uses these credentials only when needed. This means that if the credentials provided are invalid, we’ll only find out when we interact with the API in ways that require authentication. If we use any API methods that work in an anonymous way then these will continue to work.

4. Myself and Other Users

Once we’ve created a client, we can start to interact with the GitHub API.

If we’ve got a correctly authenticated client then we can use this to query the user that we’re authenticated as – known as Myself:

GHMyself myself = gitHub.getMyself();

We can then use this object to query the current user:

assertEquals("someone", myself.getLogin());
assertEquals("someone@example.com", myself.getEmail());
assertEquals(50, myself.getFollows().size());

We’re also able to query the details of other users as well:

GHUser user = gitHub.getUser("eugenp");
assertEquals("eugenp", user.getLogin());
assertEquals(2, user.getFollows().size());

This returns a GHUser, which is the superclass of GHMyself. As such, there are certain things that we can do with the GHMyself object – representing the current authenticated user – that we can’t do with any other users. These include:

  • Managing public keys
  • Managing email addresses
  • Managing organisation memberships

However, anything that expects a GHUser can also accept a GHMyself as well.

5. Repositories

We can also work with repositories, as well as with users. This will include the ability to query the list of repositories owned by a user, but also to access the contents of a repository and even make changes to it.

Note that all repositories in GitHub are owned by exactly one user, and so we need to know the username as well as the repository name to be able to correctly access them.

5.1. Listing Repositories

If we’ve got a GHUser object – or GHMyself – then we can use this to get the repositories that this user owns. This is achieved using listRepositories():

PagedIterable<GHRepository> repositories = user.listRepositories();

This gives us a PagedIterable since there might be a very large number of these repositories. By default, this works with a page size of 30, but we can specify this when listing the repositories if needed:

PagedIterable<GHRepository> repositories = user.listRepositories(50);

This then gives us a number of ways to access the actual repositories. We can convert it to Array, List or Set types containing the entire collection of repositories:

Array<GHRepository> repositoriesArray = repositories.toArray();
List<GHRepository> repositoriesList = repositories.toList();
Set<GHRepository> repositoriesSet = repositories.toSet();

However, these will fetch everything up front – which can be expensive if there are a very large number. For example, the Microsoft user currently has 6,688 repositories. At 30 repositories per page, this would take 223 API calls to collect the full list.

Alternatively we can obtain an iterator over the repositories. This will then only make API calls on demand, allowing us much more efficient access to the collection:

Iterator<GHRepository> repositoriesSet = repositories.toIterator();

Even easier though, the PagedIterable is itself an Iterable and can be used directly anywhere this is applicable – for example, in an enhanced-for loop:

Set<String> names = new HashSet<>();
for (GHRepository ghRepository : user.listRepositories()) {
    names.add(ghRepository.getName());
}

This simply iterates over every returned repository and extracts their names. Because we’re using the PagedIterable this will act like a normal Iterable but will make API calls behind the scenes only when necessary.

5.2. Directly Accessing Repositories

As well as listing repositories, we can directly access them by name. If we’ve got the appropriate GHUser then we only need the repository name:

GHRepository repository = user.getRepository("tutorials");

Alternatively, we can access the repository directly from our client. In this case, we need the full name comprising of the username and repository name combined into a single string:

GHRepository repository = gitHub.getRepository("eugenp/tutorials");

This then gives us the exact same GHRepository object as if we’d navigated through the GHUser object.

5.3. Working With Repositories

Once we’ve got a GHRepository object, we can start to interact with this directly.

At the simplest level, this allows us to retrieve repository details such as its name, owner, creation date, and more.

String name = repository.getName();
String fullName = repository.getFullName();
GHUser owner = repository.getOwner();
Date created = repository.getCreatedAt();

However, we can also query the contents of the repository. We can do this by treating it as a Git repository – allowing access to branches, tags, commits, and so on:

String defaultBranch = repository.getDefaultBranch();
GHBranch branch = repository.getBranch(defaultBranch);
String branchHash = branch.getSHA1();
GHCommit commit = repository.getCommit(branchHash);
System.out.println(commit.getCommitShortInfo().getMessage());

Alternatively, if we know the full names then we can access the full contents of files:

String defaultBranch = repository.getDefaultBranch();
GHContent file = repository.getFileContent("pom.xml", defaultBranch);
String fileContents = IOUtils.toString(file.read(), Charsets.UTF_8);

If they exist, we can also access certain special files – specifically, the readme and license:

GHContent readme = repository.getReadme();
GHContent license = repository.getLicenseContent();

These work exactly the same as accessing the file directly, but without needing to know the filename. In particular, GitHub supports a range of different filenames for these concepts and this will return the correct one.

5.4. Manipulating Repositories

As well as reading repository content, we can also make changes to them.

This can include updating the configuration of the repository itself, allowing us to do things like changing the description, home page, visibility, and so on:

repository.setDescription("A new description");
repository.setVisibility(GHRepository.Visibility.PRIVATE);

We’re also able to fork other repositories into our own account:

repository.createFork().name("my_fork").create();

We can also create branches, tags, pull requests and other things:

repository.createRef("new-branch", oldBranch.getSHA1());
repository.createTag("new-tag", "This is a tag", branch.getSHA1(), "commit");
repository.createPullRequest("new-pr", "from-branch", "to-branch", "Description of the pull request");

It’s even possible to create entire commits if we need to, though this is much more involved.

6. Conclusion

In this article, we’ve taken a very brief look at the GitHub API For Java library. There’s much more that can be done using this library. Next time you need to work with the GitHub API, why not give it a try.

As usual, all of the examples from this article are available over on GitHub.

The post Java API for GitHub using GitHub-API first appeared on Baeldung.
       

Viewing all articles
Browse latest Browse all 3666

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>