API Testing using Java


images (4)

What is API :
An application-programming interface (API) is a set of programming instructions and standards for accessing a Web-based software application or Web tool.

Example :

An API is a software-to-software interface, not a user interface. With APIs, applications talk to each other without any user knowledge or intervention. When you buy movie tickets online and enter your credit card information, the movie ticket Web site uses an API to send your credit card information to a remote application that verifies whether your information is correct. Once payment is confirmed, the remote application sends a response back to the movie ticket Web site saying it’s OK to issue the tickets.

What is JSON :

JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. JSON can represent two structured types: objects and arrays. An object is an unordered collection of zero or more name/value pairs. An array is an ordered sequence of zero or more values. The values can be strings, numbers, booleans, null, and these two structured types.

Example : You can see it here.

JSON is an easier-to-use alternative to XML.

Note : Here i am just conferring how to parse and How to convert JsonObject to Java Object.So that you could use it your live projects using selenium.
 Application contentType : Json

Objective : To validate Address : Chicago, IL, USA.
GoogleMaps API : http://maps.googleapis.com/maps/api/geocode/json?address=chicago&sensor=false

We can easily parse Json using “json-lib-2.4-jdk15.jar”  Download from here…!

Please consider the below code as a reference.

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

import org.json.JSONArray;
import org.json.JSONObject;
import org.testng.Reporter;
import org.testng.annotations.Test;

public class ReadJsonObject{
@Test
public void aptTesting() throws Exception {
try {
URL url = new URL(
http://maps.googleapis.com/maps/api/geocode/json?address=chicago&sensor=false”);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(“GET”);
conn.setRequestProperty(“Accept”, “application/json”);

if (conn.getResponseCode() != 200) {
throw new RuntimeException(” HTTP error code : ”
+ conn.getResponseCode());
}

Scanner scan = new Scanner(url.openStream());
String entireResponse = new String();
while (scan.hasNext())
entireResponse += scan.nextLine();

System.out.println(“Response : “+entireResponse);

scan.close();

JSONObject obj = new JSONObject(entireResponse );
String responseCode = obj.getString(“status”);
System.out.println(“status : ” + responseCode);

JSONArray arr = obj.getJSONArray(“results”);
for (int i = 0; i < arr.length(); i++) {
String placeid = arr.getJSONObject(i).getString(“place_id”);
System.out.println(“Place id : ” + placeid);
String formatAddress = arr.getJSONObject(i).getString(
“formatted_address”);
System.out.println(“Address : ” + formatAddress);

//validating Address as per the requirement
if(formatAddress.equalsIgnoreCase(“Chicago, IL, USA”))
{
System.out.println(“Address is as Expected”);
}
else
{
System.out.println(“Address is not as Expected”);
}
}

conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}
}

That’s it, Now you know to convert JsonObject to Java Object and use it in your Selenium snippet.

You can Practice using API : http://restcountries.eu/rest/v1

Wanna know about basics? Click Here for Basics

Smart way of Rest API Testing – Simple REST API Testing Framework

Advertisements

46 thoughts on “API Testing using Java

  1. Richard July 27, 2015 / 12:10 am

    It’s really helpful dude.thank-you keep posting

    Like

  2. sandhyaa July 27, 2015 / 12:12 am

    What is 200 in that code? why did you put 200 ? Please explain

    Like

  3. sandhyaa July 27, 2015 / 12:00 pm

    Thankyou ALL. Thanks a ton for the post Charan.

    Like

  4. Anonymous July 28, 2015 / 11:12 pm

    WOW This is the best way.Thankyou Charan.

    Like

  5. Anonymous July 29, 2015 / 4:38 pm

    Hi I m getting the below mentioned error

    Response : { “results” : [ { “address_components” : [ { “long_name” : “Chicago”, “short_name” : “Chgo”, “types” : [ “locality”, “political” ] }, { “long_name” : “Cook County”, “short_name” : “Cook County”, “types” : [ “administrative_area_level_2”, “political” ] }, { “long_name” : “Illinois”, “short_name” : “IL”, “types” : [ “administrative_area_level_1”, “political” ] }, { “long_name” : “United States”, “short_name” : “US”, “types” : [ “country”, “political” ] } ], “formatted_address” : “Chicago, IL, USA”, “geometry” : { “bounds” : { “northeast” : { “lat” : 42.023131, “lng” : -87.52404399999999 }, “southwest” : { “lat” : 41.6443349, “lng” : -87.9402669 } }, “location” : { “lat” : 41.8781136, “lng” : -87.6297982 }, “location_type” : “APPROXIMATE”, “viewport” : { “northeast” : { “lat” : 42.023131, “lng” : -87.52404399999999 }, “southwest” : { “lat” : 41.6443349, “lng” : -87.9402669 } } }, “place_id” : “ChIJ7cv00DwsDogRAMDACa2m4K8”, “types” : [ “locality”, “political” ] } ], “status” : “OK”}
    Exception in thread “main” org.json.JSONException: A JSONObject text must begin with ‘{‘ at character 1 of str
    at org.json.JSONTokener.syntaxError(JSONTokener.java:451)
    at org.json.JSONObject.(JSONObject.java:179)
    at org.json.JSONObject.(JSONObject.java:326)
    at javaprogram.org.com.ReadJsonObject.main(ReadJsonObject.java:50)

    Like

    • Anonymous August 11, 2015 / 2:15 pm

      set the ‘str’ to some String.i think we did not declare str in the code

      Like

  6. vedavyasa August 18, 2015 / 9:57 pm

    Use postman to automate API because this helps a lot to replicate the same thing in codes

    Like

    • charan163 August 18, 2015 / 10:05 pm

      Yes, I do agree.This post says that we can also test the API in this way where it can be integrated with functional test scripts.

      Kind Regards

      Like

  7. Shri October 4, 2015 / 8:07 am

    Hi, could you please give example of XML Instead of JSON . thanks

    Like

  8. chaitanya October 15, 2015 / 10:28 pm

    Nice post.Thank you.

    Like

  9. Sachin Gupta November 27, 2015 / 4:05 pm

    Nice post, could you please give example how to post value for API testing same as above example?

    Like

    • charan163 November 28, 2015 / 10:33 am

      Hi, It’s quite simple. Here’s a sample code

      HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead

      try {
      HttpPost request = new HttpPost(“http://yoururl”);
      StringEntity params =new StringEntity(“details={\”name\”:\”myname\”,\”age\”:\”20\”} “);
      request.addHeader(“content-type”, “application/x-www-form-urlencoded”);
      request.setEntity(params);
      HttpResponse response = httpClient.execute(request);

      // handle response here…
      }catch (Exception ex) {
      // handle exception here
      }

      Like

  10. Vaibhav Sharma December 8, 2015 / 3:10 pm

    I am getting following error :
    FAILED: aptTesting
    java.lang.UnsupportedClassVersionError: org/json/JSONObject : Unsupported major.minor version 52.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at com.example.ReadJsonObject.aptTesting(ReadJsonObject.java:37)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:648)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:834)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1142)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:124)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
    at org.testng.TestRunner.privateRun(TestRunner.java:771)
    at org.testng.TestRunner.run(TestRunner.java:621)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:357)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:352)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:310)
    at org.testng.SuiteRunner.run(SuiteRunner.java:259)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1176)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1101)
    at org.testng.TestNG.run(TestNG.java:1009)
    at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)

    Need your suggestion.

    Like

    • charan163 December 9, 2015 / 9:46 am

      Hi,
      What are you trying parse? Please share the Code.Is that your service URL?

      Like

    • charan163 December 9, 2015 / 9:48 am

      Generally
      java.lang.UnsupportedClassVersionError happens because of a higher JDK during compile time and lower JDK during runtime.Please chck the JDK version

      Like

  11. Sanket P January 20, 2016 / 8:31 am

    We are waiting for next post on — Smart way of Rest API Testing using Selenium Webdriver

    Like

  12. Vikash kumar February 4, 2016 / 4:43 pm

    Really nice explanation!!

    The information that you have provided is very useful. If anyone want to lean more, he/she can visit Selenium Testing

    Like

  13. Anonymous February 11, 2016 / 12:30 pm

    JSONObject obj = new JSONObject(entireResponse ); is wrong as JSON class does not conatin this constructor

    Like

  14. Manisha Sah March 2, 2016 / 7:38 pm

    Hi,

    How do I handle the response for POST request which has input in xml in body :

    <!—->

    1
    0
    10

    HOST OS

    Microsoft Windows Server 2008 R2 EE (64-bit, x64)

    Microsoft Windows Server 2008 R2 EE (SP2 64-bit, x64)

    Protocol

    FC

    FCoE

    I am using the rest client and shows the response fine.
    please help.

    -manisha

    Like

    • Admin March 3, 2016 / 1:50 pm

      We can use XML parser to parse xml body for SOAP services. Well this post kindred to JSON.
      But the proc is similar, you can integrate with your Selenium testscripts (depends on the functionality).

      Ex: Parse the XML and get the required data from the response. Now compare the response with your Test Data. This will suffice

      Thanks & Regards

      Like

      • Manisha Sah March 3, 2016 / 2:29 pm

        Thanks Admin.
        My question is more on how do I pass the XML body in the POST request?

        try {
        HttpPost url = new HttpPost(“http://imt_lb_stg.corp.netapp.com:8080/IMTService/rest/results/getCompatibility?”);
        StringEntity params =new StringEntity(“details={\”APPLICATION_KEY\”:\”tests\”,\”APPLICATION_TOKEN\”:\”P5II8NewdFGNPD2%2BWinUpg%3D%3D\”} “);
        url.addHeader(“content-type”, “application/xml”);
        url.addHeader(“content-type”, “application/xml”);
        url.setEntity(params);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpResponse response = httpClient.execute(url);

        I get error on line –> HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        Also not clear what is url.setEntity(params);

        Along with this application key and token, I need to pass few more values in request body for post as :

        3
        0
        1000

        Protocol

        FC

        Like

  15. Ravi March 8, 2016 / 1:10 pm

    Hi, what change we need to do in case of Post instead of Get. i am passing POST in below
    conn.setRequestMethod(“POST”). but getting error.

    Like

    • Anonymous April 25, 2016 / 1:14 pm

      Request you to Please post an example of POST request for any Generic Scenario.

      Thanks in Advance.

      Like

  16. Anonymous March 13, 2016 / 11:40 am

    Thanks to author for this. While trying to execute this code, I noticed JSONObject and JSONArray are not present as part of the json-lib-2.4-jdk15.jar

    Like

  17. Prabhu March 13, 2016 / 2:47 pm

    Not able to resolve jsobject and jsarray as type

    Like

  18. Prabhu March 13, 2016 / 2:48 pm

    Thanks

    Like

  19. Naveen April 26, 2016 / 9:32 am

    How come Selenium comes to picture in the above code , it’s plain Java code

    Like

    • Hari Charan April 26, 2016 / 7:22 pm

      Hi Naveen,
      Yes I do agree it’s plain Java code but I’m validating formatted_address. Can’t we integrate this with Selenium API to test your application functionalities? You should be intelligent enough to use it your framework. Let me give you a hint

      Scenario: I need to check the data published from dashboard (web app) should be displayed in mobile apps too.
      What are we supposed to do?
      This is just an example to elucidate. My objective is to check the app functionality and at the same I’m testing API too. So integrating with selenium shouldn’t be useless.

      Thanks.

      Like

  20. Deepu Bn May 3, 2016 / 1:47 pm

    Hi,I am waiting from long time for you new Smart way of Rest API Testing using Selenium Webdriver will be posted soon.When is this expected.

    Like

  21. Girish Chavan May 6, 2016 / 1:49 am

    JSONObject does not accept any parameter into the constructor.
    So JSONObject jobj = new JSONObject(entireResponse)
    shows error as “Remove argument to match JSONObject
    Can you explain plz

    Like

    • Anonymous July 18, 2016 / 6:56 pm

      Facing the similar issue

      Like

    • Anonymous September 6, 2016 / 2:40 pm

      Facing same issue.. pls help

      Like

  22. Anonymous July 18, 2016 / 5:34 pm

    Hi, How can we pass API-key through this code when endpoint is not open

    Thanks in Advance…..

    Like

  23. Anonymous January 24, 2017 / 3:56 am

    How to continue to run the automation with same Jsession ID.

    Like

  24. Ravi Kumar February 20, 2017 / 12:32 pm

    Good One … Very helpful.. thanks for sharing

    Like

  25. Nikhil March 16, 2017 / 2:11 pm

    How do i Post multi array json??? using this format

    (“/posts”, “{\”token\”:”+passtoken+” , \”id\”:\”49602\”}”, “application/json”)

    Like

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s