Creating a Java API Client for GitHub Repos in Under 50 Lines

Creating a Java API Client for GitHub Repos in Under 50 Lines

Creating a Java API Client for GitHub Repos in Under 50 Lines

 

When you’re starting out with REST API integrations in Java, GitHub provides an excellent hands-on opportunity. In this blog post, we’ll walk through building a lightweight Java application that fetches public repositories of any GitHub user using the GitHub REST API — in under 50 lines of code.

We’ll use Java’s `HttpURLConnection` for making HTTP requests and the popular `org.json` library to parse JSON responses. You’ll see a simple yet powerful method for data retrieval, which can also be extended for more complex API operations later on.

1. Setting Up the Project

This example works in any standard Java setup — from IDEs like IntelliJ or Eclipse to a simple terminal-based environment. Make sure you’re running Java 8 or higher.

For JSON parsing, we’ll use the org.json package. You can include the library via Maven like so:

<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20230227</version>
</dependency>

Alternatively, download the JAR directly from mvnrepository.com and add it to your project classpath.

2. Understanding the GitHub API Endpoint

GitHub’s REST API is well-documented and easy to consume. The endpoint we’ll hit is:

https://api.github.com/users/{username}/repos

This returns a JSON array of public repositories for the specified user, each containing metadata such as repository name, URL, description, and more.

No authentication is needed for public repos, although rate-limiting applies when unauthenticated (usually 60 requests/hour).

3. Writing the Java Code

Below is the full Java class that fetches and prints the names and URLs of public repositories for a given user:

import java.io.*;
import java.net.*;
import org.json.*;

public class GitHubRepos {
    public static void main(String[] args) throws Exception {
        String username = "octocat"; // replace with any GitHub username
        URL url = new URL("https://api.github.com/users/" + username + "/repos");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        JSONArray repos = new JSONArray(response.toString());
        for (int i = 0; i < repos.length(); i++) {
            JSONObject repo = repos.getJSONObject(i);
            System.out.println(repo.getString("name") + " - " + repo.getString("html_url"));
        }
    }
}

What’s Happening Here:

  • We form the API URL using the provided username.
  • An HTTP GET request is made using `HttpURLConnection`.
  • We read the response stream line-by-line into a `StringBuilder`.
  • The JSON string is parsed into a `JSONArray`, and we iterate to print each repo’s name and URL.

4. Tips and Improvements

Here are a few tips for working with API clients like this one:

  • Error handling: Always check for HTTP response codes. In production code, wrap connections and streams with try-with-resources and catch `IOException` or `JSONException` gracefully.
  • Rate-limiting: GitHub applies rate limits. To avoid hitting the limit, use authenticated requests with a personal access token.
  • Pagination: GitHub returns results in pages (30 items per page by default). Look into the `Link` header for retrieving additional pages if needed.
  • JSON parser alternatives: For more advanced parsing, consider using libraries like Jackson or Gson.
  • Reusability: Turn this logic into a reusable method or class for API integration layers in larger applications.

5. Conclusion and Takeaways

In under 50 lines of code, we’ve created a fully functional GitHub API client in Java that fetches and displays public repositories of any user. This starter project can now be extended to include features like pagination, authentication, repo filtering, or even integration into a GUI or web application.

By learning how to make HTTP requests and parse JSON in core Java, you’ve taken a big step toward building more powerful and connected Java applications. Happy coding!

 

Useful links: