Srikanth Technologies

Accessing GitHub.Com Rest API from Spring

In this blog, I show how to access Rest API provided by GitHub.Com using RestTemplate in Spring Framework. In case you didn't get started with Spring Framework yet then go to my blog Getting Started With Spring Framework to get up and running with Spring.

Additions To POM file

In order to access Restful services provided by GitHub.Com (any other website for that matter), we need to add the following dependencies in POM.XML file.

Here is complete POM.XML file that includes dependencies required to use RestTemplate (spring-web) and convert JSON to Java (jackson-databind).

  <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>st.com</groupId>
	<artifactId>springdemo</artifactId>
	<version>1.0-SNAPSHOT</version>

	<properties>
		<spring-framework.version>4.3.3.RELEASE</spring-framework.version>
	</properties>

	<dependencies>
		<!-- Spring Framework -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>
		<!-- Needed for RestTemplate -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring-framework.version}</version>
		</dependency>

                <!-- Used for Java to JSON and JSON to Java conversion -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.7.3</version>
		</dependency>
		
	</dependencies>
	<!-- Needed to use Java 8 -->
	<build>
		<finalName>springdemo</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.3</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>
Before we write a program to retrieve details of a user from GitHub.Com using Restful service, we need to understand the URL and format of the data provided by Restful service.

The following URL is used to get information about a single user - srikanthpragada.

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

Example: https://api.github.com/users/srikanthpragada  

When you give the above URL, it returns the following JSON.
 
{
  "login": "srikanthpragada",
  "id": 11234226,
  "avatar_url": "https://avatars0.githubusercontent.com/u/11234226?v=3",
  "gravatar_id": "",
  "url": "https://api.github.com/users/srikanthpragada",
  "html_url": "https://github.com/srikanthpragada",
  "followers_url": "https://api.github.com/users/srikanthpragada/followers",
  "following_url": "https://api.github.com/users/srikanthpragada/following{/other_user}",
  "gists_url": "https://api.github.com/users/srikanthpragada/gists{/gist_id}",
  "starred_url": "https://api.github.com/users/srikanthpragada/starred{/owner}{/repo}",
  "subscriptions_url": "https://api.github.com/users/srikanthpragada/subscriptions",
  "organizations_url": "https://api.github.com/users/srikanthpragada/orgs",
  "repos_url": "https://api.github.com/users/srikanthpragada/repos",
  "events_url": "https://api.github.com/users/srikanthpragada/events{/privacy}",
  "received_events_url": "https://api.github.com/users/srikanthpragada/received_events",
  "type": "User",
  "site_admin": false,
  "name": "Srikanth Pragada",
  "company": "Srikanth Technologies",
  "blog": "http://www.srikanthtechnologies.com",
  "location": "Visakhapatnam, Andhra Pradesh, India",
  "email": "srikanthpragada@gmail.com",
  "hireable": null,
  "bio": null,
  "public_repos": 42,
  "public_gists": 1,
  "followers": 89,
  "following": 0,
  "created_at": "2015-02-27T18:37:39Z",
  "updated_at": "2017-03-09T16:31:41Z"
}

Getting Information About A Single User

Now, we write a Java program that uses Spring's RestTemplate to read details of a user by using the above Restful API.

We need to create a Java class to represent data sent by Rest API. Data is sent in the form of JSON and we convert that to Java object using Jackson. Annotation @JsonIgnoreProperties specifies that Jackson should ignore properties in JSON that are not present in Java class.

GitHubUser.java

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class GitHubUser {
	private String login, email, company, location, created_at;
	public String getLogin() {
		return login;
	}
	public void setLogin(String login) {
		this.login = login;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getCompany() {
		return company;
	}
	public void setCompany(String company) {
		this.company = company;
	}
	public String getLocation() {
		return location;
	}
	public void setLocation(String location) {
		this.location = location;
	}
	public String getCreated_at() {
		return created_at;
	}
	public void setCreated_at(String created_at) {
		this.created_at = created_at;
	}
}

GetGitHubUserInfo.java

The following program reads data about a user from Rest API and copies data from that JSON object to GitHubUser object.

import org.springframework.web.client.RestTemplate;	

public class GetGitHubUserInfo {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        GitHubUser user = restTemplate.getForObject("https://api.github.com/users/srikanthpragada", GitHubUser.class);
        
        System.out.println("Login   :    " + user.getLogin());
        System.out.println("Email   :    " + user.getEmail());
        System.out.println("Company :    " + user.getCompany());
        System.out.println("Location:    " + user.getLocation());
        System.out.println("Created :    " + user.getCreated_at());
    }
}
When you run the above program, the following output is produced. Try this program with different GitHub users.

Login   :    srikanthpragada
Email   :    srikanthpragada@gmail.com
Company :    Srikanth Technologies
Location:    Visakhapatnam, Andhra Pradesh, India
Created :    2015-02-27T18:37:39Z

Getting List Of Repos of a User

GitHub provides a different URL to get information about all repositories related to a user. The following is the URL.

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

Example: https://api.github.com/users/srikanthpragada/repos 

The following is the format in which GitHub returns data about Repositories when the above URL is given. As we can see, it is an array of JSON objects where each object contains information about repo and its owner.

[
  {
    "id": 50039390,
    "name": "android",
    "full_name": "srikanthpragada/android",
    "owner": {
      "login": "srikanthpragada",
      "id": 11234226,
      "avatar_url": "https://avatars0.githubusercontent.com/u/11234226?v=3",
      "gravatar_id": "",
      "url": "https://api.github.com/users/srikanthpragada",
      // other details
    },
    "private": false,
    "html_url": "https://github.com/srikanthpragada/android",
    "description": "Android Programs",
    // other details
  },
  {
    "id": 59585248,
    "name": "android_code",
    "full_name": "srikanthpragada/android_code",
    "owner": {
      "login": "srikanthpragada",
      "id": 11234226,
      "avatar_url": "https://avatars0.githubusercontent.com/u/11234226?v=3",
      "gravatar_id": "",
      "url": "https://api.github.com/users/srikanthpragada",
      // other details
    },
    "private": false,
    "html_url": "https://github.com/srikanthpragada/android_code",
    "description": "Android Code Examples",
    // other details
  }
  // remaining details of other repos 
 ]

The following program lists all repostories of user srikanthpragada. As this API returns an array of objects, RestTemplate returns a List of Map objects where each key in Map object refers to an attribute (field) in JSON object.


import java.util.LinkedHashMap;
import java.util.List;
import org.springframework.web.client.RestTemplate;	

public class ListUserRepos {
    public static void main(String[] args) {
    	  RestTemplate restTemplate = new RestTemplate();
          List<LinkedHashMap<String,String>> repos = restTemplate.getForObject("https://api.github.com/users/srikanthpragada/repos", List.class);
          
          for(LinkedHashMap<String,String>  repo : repos)
          { 
           	System.out.println(repo.get("name"));
          }
    }
}
The following is the output of the above program.

android
android_code
android_device_features
android_feb_2
android_storage
angularjs
angular_22_jan
csharp
c_june3_2016
c_language
dec_1_javaee
dec_1_javaee_web
dec_22_csharpdemo
dec_22_mvcdemo
dec_22_webdemo
feb20_webdemo
feb_19_springcore
feb_19_springmvc
First
hibernate_demo
javaee
javascript
javase
jdbc
jQuery
jsf
june13_mvcdemo
june13_webdemo
june20_webdemo
maven_restdemo

GitHub provides information about its Rest API at https://developer.github.com/v3/.