APIs and HTTP Client: GET Call

In this article, we will use one of the Java libraries that is the HTTP Client library, to call and validate the GET Request

Prem Singh Rathore
6 min readAug 20, 2021
Image source: Google

Here is the link to the Rest APIs, which we are gonna be using.

To create a new project in eclipse checkout step 1 in the article below 👇

Note: You can name your project anything you want but to be on the same page, let’s give HTTP Client in artifact id and RestAPI in group id.

HTTP Client Project Hierarchy

We can remove the JUnit dependency from the pom.xml file and add the required dependencies.

<dependency>
<groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId><artifactId>httpcore</artifactId>
<version>4.4.13</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160212</version>
</dependency>

And, your pom.xml will look something like this:

pom.xml file

With all the required dependencies in place, now we can start writing our code.

Let’s create one properties file to drive the global value from it.

Properties File

We will define the base URL and an endpoint in the properties file

URL = https://reqres.in/
serviceURL = /api/users

Now, we need to create one base class under a new package called the base.

Test Base Class

Test Base class will act as a parent for other classes.

We need to define one constructor in the base class to read values from the properties file.

public TestBase(){public Properties prop;try { prop = new Properties(); 
FileInputStream ip = new FileInputStream(“C:\Users\prem.rathore\eclipse-workspace\HTTPClient\src\main\java\config\config.properties”);
prop.load(ip);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
}

The File Input Stream method contains the path of your properties file.

We need to create one Rest Client class under a new package called client.

Rest Client Class

And, create a GET method inside the Rest Client class.

public void get(String url){}

Create an object for the HTTP Clients class to create one client connection.

public void get(String url){ CloseableHttpClient httpClient = HttpClients.createDefault();}

Create an object for the HTTP Get class.

public void get(String url){CloseableHttpClient httpClient = HttpClients.createDefault();HttpGet httpget = new HttpGet(url); // http get request}

Now, we will hit the URL using the execute method and store the response in the Closeable HTTP Response object.

public void get(String url){CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(url); // http get request CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpget); // hit the url}

Below is the response you will get once you hit the URL in Postman

{
"page": 1,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 1,
"email": "george.bluth@reqres.in",
"first_name": "George",
"last_name": "Bluth",
"avatar": "https://reqres.in/img/faces/1-image.jpg"
},
{
"id": 2,
"email": "janet.weaver@reqres.in",
"first_name": "Janet",
"last_name": "Weaver",
"avatar": "https://reqres.in/img/faces/2-image.jpg"
},
{
"id": 3,
"email": "emma.wong@reqres.in",
"first_name": "Emma",
"last_name": "Wong",
"avatar": "https://reqres.in/img/faces/3-image.jpg"
},
{
"id": 4,
"email": "eve.holt@reqres.in",
"first_name": "Eve",
"last_name": "Holt",
"avatar": "https://reqres.in/img/faces/4-image.jpg"
},
{
"id": 5,
"email": "charles.morris@reqres.in",
"first_name": "Charles",
"last_name": "Morris",
"avatar": "https://reqres.in/img/faces/5-image.jpg"
},
{
"id": 6,
"email": "tracey.ramos@reqres.in",
"first_name": "Tracey",
"last_name": "Ramos",
"avatar": "https://reqres.in/img/faces/6-image.jpg"
}
],
"support": {
"url": "https://reqres.in/#support-heading",
"text": "To keep ReqRes free, contributions towards server costs are appreciated!"
}
}

Fetching information from the GET call response 🔁

To print the status code of the response, we can use below code

int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();System.out.println(“Status Code →”+statusCode);

We can also print the response string using the Entity Utils and JSON Object class

String responseString = EntityUtils.toString(closeableHttpResponse.getEntity(), "UTF-8");JSONObject responseJson = new JSONObject(responseString);System.out.println("Response Json from GET API-->"+responseJson);

We can print all the Headers with the help of Hash Map

Header[] headersArray = closeableHttpResponse.getAllHeaders();HashMap<String, String> allHeaders = new HashMap<String, String>();for (Header header : headersArray) {allHeaders.put(header.getName(), header.getValue());
}
System.out.println("Headers Array: " + allHeaders);

Creating our first Test case in the Get API Test class

Let’s create one Get API Test class under the Test package 📦

Get API Test Class

We will define one Setup method to call the constructor of the Base class (TestBase.java)

package Tests;import org.testng.annotations.BeforeMethod;import base.TestBase;public class GetAPITest extends TestBase {TestBase testBase;
String mainURL;
String apiURL;
String URL;
@BeforeMethod
public void setUp() {
testBase = new TestBase();
mainURL = prop.getProperty("URL");
apiURL = prop.getProperty("serviceURL");
URL = mainURL + apiURL;}}

Note: Make sure you inherit the base class using extends keyword

We will create one Test case to run the code and print all the response-related information in the console.

@Test
public void getTest() throws ClientProtocolException, IOException {
RestClient restClient = new RestClient();
restClient.get(URL);
}

Running the Test cases with TestNG ☕

Go to the Get API Test class, right-click and Run As one TestNG test

Get API Test Class

Let’s run the Test cases now

Console Window

Ah oh 🤔

Don’t worry we got this error because we don’t have the TestNG Library configured in the Project.

You can do it by going to the Properties window of the Project

Build Path Config

In the properties, window click on Add Library

Properties Window

Select TestNG Library and click on the Next button

Add Library Window

And Finish

Finish Setup

And you will see the TestNG library under Libraries

Java Build Path

let’s run the Test case and see if it is working fine

Console Window

Awesome!

So, that was about automating the Rest Get call using HTTP Client.

In the next part, we will see how to validate the JSON response and, I will also be sharing the Git repo link at the end of the series.

Thanks for reading.

Here is the Git repo for you to download the code.

Declaration: This article is based on one of the videos by Naveen AutomationLabs and, the video link is below.

https://www.youtube.com/watch?v=qwc5A55MIYU&list=PLFGoYjJG_fqp891lruz5fCRPWsDtEXJky

--

--