Tuesday, October 4, 2016

API testing: Get requests with Java and Apache libraries


API testing is very common nowadays, and it's easy to see why. One of the uses of APIs is to manipulate an application to create pre steps (among a lot of other things) for scenarios without the need of handling the UI, which is good news for all who struggle with locators that change a lot.

In this article I will show how to use Java to perform basic API actions with the Apache HttpComponents. Let's check it out:

Requirements:
Steps:

1. Open Eclipse and create a new Java Project. Call it 'APITesting'
Project details

2. Right click src > New > Class. Name the new class 'APITesting'. Select 'public static void main(String[] args)' to create the main method snippet. Then click Finish.

Class details

Class created

3. Add the needed libraries. For this, expand the APITesting project and right click JRE System Library > Build Path > Configure Build Path...
4. Click 'Add External JARs'
5. Navigate to httpcomponents-client-4.5.2\lib and select the following libraries:
  • httpClient-4.5.2.jar
  • httpcore-4.4.4.jar
  • commons-logging-1.2.jar
Then press OK.
6. Now that you have all the required libraries, enter the following code into the APITesting.java class. The final result should look like this:


So, basically, you have to perform 3 main actions here:

- Create a httpClient:

HttpClient httpClient = HttpClientBuilder.create().build();

- Create a GET request with proper endpoint and add the header:

HttpGet getRequest = new HttpGet(
"https://jsonplaceholder.typicode.com/posts");
getRequest.addHeader("accept", "application/json");

- Execute the request and store the result in a HttpResponse:

HttpResponse response = httpClient.execute(getRequest);

From there on, you can play with the contents of the response and print it, as I did in this example. Click the Play button in Eclipse to run the code. You should see a json text as response in the console:

Response

1 comment: