Core Java

GitHub Access with Java

The GitHub API enables developers to programmatically interact with GitHub’s services. Using the github-api Java client library (developed by Kohsuke Kawaguchi), you can connect to GitHub, manage repositories, issues, pull requests, and much more directly from Java code. Let us delve into understanding how the Java GitHub API can be used to seamlessly interact with GitHub repositories and automate common developer workflows.

1. Introduction to GitHub and GitHub API

GitHub is a widely used platform for hosting, managing, and collaborating on software projects using the Git version control system. It enables developers and teams to track changes, collaborate efficiently, and manage code through features like pull requests, issues, actions, and more.

The GitHub REST API allows developers to programmatically interact with GitHub resources such as repositories, users, commits, and workflows over HTTP. It supports a range of use cases including automating repository creation, retrieving user data, and integrating GitHub functionalities into external applications.

2. Code Example

This section demonstrates how to integrate and use the GitHub API in a Java application using the org.kohsuke.github library. This library abstracts low-level HTTP calls and lets Java developers interact with GitHub as if they were working with local Java objects, making it easier to authenticate, list repositories, create new ones, and fetch metadata without writing manual request logic. We’ll start by adding the necessary dependency to your project and then walk through the Java implementation.

2.1 Add Dependency (pom.xml)

To use the GitHub API library in your Java project, you need to include the following Maven dependency in your pom.xml file.

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

2.2 Java Code

Below is the main Java code that defines the GitHubManager class. This class provides functionality to connect to GitHub using an OAuth token, retrieve user information, list repositories, create new repositories, fetch repository details, and optionally delete a repository. It uses methods from the GitHub API to interact with the authenticated user’s GitHub account.

package com.jcg.example;

import org.kohsuke.github.*;

import java.io.IOException;
import java.util.Map;

public class GitHubManager {

    // GitHub API client instance
    private final GitHub github;

    // Constructor: connects to GitHub using a personal access token
    public GitHubManager(String token) throws IOException {
        this.github = GitHub.connectUsingOAuth(token);
    }

    // Prints the authenticated user's login, name, and email
    public void printAuthenticatedUser() throws IOException {
        GHMyself user = github.getMyself(); // Fetch authenticated user
        System.out.println("Authenticated as: " + user.getLogin());
        System.out.println("Name: " + user.getName());
        System.out.println("Email: " + user.getEmail());
    }

    // Lists all repositories of the authenticated user
    public void listRepositories() throws IOException {
        System.out.println("\nListing repositories:");
        Map repos = github.getMyself().getRepositories(); // Fetch repos
        for (GHRepository repo : repos.values()) {
            System.out.println("Repo: " + repo.getName() + ", Private: " + repo.isPrivate());
        }
    }

    // Creates a new GitHub repository with the given name, description, and privacy setting
    public void createRepository(String name, String description, boolean isPrivate) throws IOException {
        System.out.println("\nCreating repository: " + name);
        GHCreateRepositoryBuilder builder = github.createRepository(name);
        builder.description(description)     // Set description
               .private_(isPrivate)          // Set visibility
               .autoInit(true)               // Initialize with a README
               .create();                    // Create the repository
        System.out.println("Repository created successfully.");
    }

    // Fetches and prints details of a specific repository
    public void fetchRepositoryDetails(String repoName) throws IOException {
        GHRepository repo = github.getRepository(github.getMyself().getLogin() + "/" + repoName);
        System.out.println("\nRepository Details:");
        System.out.println("Name: " + repo.getName());
        System.out.println("Description: " + repo.getDescription());
        System.out.println("URL: " + repo.getHtmlUrl());
        System.out.println("Stars: " + repo.getStargazersCount());
    }

    // Deletes a repository owned by the authenticated user
    public void deleteRepository(String repoName) throws IOException {
        GHRepository repo = github.getRepository(github.getMyself().getLogin() + "/" + repoName);
        repo.delete(); // Delete the repository
        System.out.println("\nDeleted repository: " + repoName);
    }

    // Main method to demonstrate the usage of GitHubManager
    public static void main(String[] args) {
        try {
            // Replace with your actual GitHub personal access token
            String token = "ghp_your_personal_access_token";
            GitHubManager manager = new GitHubManager(token);

            // Display the authenticated user's profile info
            manager.printAuthenticatedUser();

            // List all repositories for the user
            manager.listRepositories();

            // Create a new repository
            String newRepo = "java-api-demo";
            manager.createRepository(newRepo, "Demo repo created via Java API", false);

            // Fetch and display details of the newly created repository
            manager.fetchRepositoryDetails(newRepo);

            // Uncomment the line below to delete the created repository
            // manager.deleteRepository(newRepo);

        } catch (IOException e) {
            e.printStackTrace(); // Print any exceptions that occur
        }
    }
}

Make a note to always store your GitHub personal access token securely using environment variables or a secure vault. Avoid hardcoding it in your source code.

2.2.1 Code Explanation

The provided Java code defines a class called GitHubManager that interacts with the GitHub API using the org.kohsuke.github library. It connects to GitHub using a personal access token and includes several methods: printAuthenticatedUser() displays the username, name, and email of the authenticated user; listRepositories() lists all repositories under the authenticated account with their names and visibility (private/public); createRepository() creates a new repository with a given name, description, and privacy setting; fetchRepositoryDetails() retrieves and prints detailed information about a specific repository, including its name, description, URL, and star count; and deleteRepository() deletes a specified repository. The main method demonstrates usage by connecting with a token, printing user details, listing existing repositories, creating a new one named java-api-demo, and showing its details. The delete function is present but commented out.

2.2.2 Code Output

Running the code produces the following output:

Authenticated as: yatinbatra
Name: Yatin Batra
Email: yatin@example.com

Listing repositories:
Repo: old-project, Private: false
Repo: sample-repo, Private: true

Creating repository: java-api-demo
Repository created successfully.

Repository Details:
Name: java-api-demo
Description: Demo repo created via Java API
URL: https://github.com/yatinbatra/java-api-demo
Stars: 0

3. Conclusion

The github-api library makes it simple and intuitive to work with GitHub in Java. You can automate workflows, build integration tools, and even manage organizational repositories using its clean object-oriented interface. This article demonstrated a full working example covering authentication, listing repositories, creating a repo, fetching repo details, and deleting a repository. You can further extend this with issue tracking, pull request management, release tagging, and more.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button