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
It’s really helpful dude.thank-you keep posting
LikeLike
What is 200 in that code? why did you put 200 ? Please explain
LikeLike
Hi Please find the Link
http://www.w3.org/Protocols/HTTP/HTRESP.html
LikeLike
It is HTTP response code OK
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
LikeLike
It’s a HTTP protocol response status code , if it’s 200 it means server returned response as
OK to HTTP request we sent to server… So now server said OK so we can continue it with script ….
LikeLike
That is HTTP Status code.. 200 code is for Success .. that means the Request is received and processed..
For More:
https://www.google.co.in/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=what%20is%20200%20error%20code
List of status code:
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
LikeLiked by 1 person
200 is response code
LikeLike
it is a status code refers to OK
http://www.restapitutorial.com/httpstatuscodes.html
LikeLike
Hi 200 is actually a response code. If the connection gets succeeded and URL open then it returns status code as 200. There are list of other code as well like 404 means page not found and so on.
Thanks & Regards,
Ankit
LikeLike
200 is the status/response code of API,if response code is 200 then we pass the test case.
LikeLike
200 is nothing but Response code. If your desired execution executes fine, it will return 200 as response code. If the code fails it will return 500
LikeLike
Thankyou ALL. Thanks a ton for the post Charan.
LikeLike
WOW This is the best way.Thankyou Charan.
LikeLike
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)
LikeLike
Hi Anonymous :)
The response is not in right form of json. You could validate json data here http://www.jsoneditoronline.org/
In your case you you paste the response its shows error about json format.
Parse your response as mention here http://theoryapp.com/parse-json-in-java/ and it should resolve your issue.
LikeLike
set the ‘str’ to some String.i think we did not declare str in the code
LikeLike
Use postman to automate API because this helps a lot to replicate the same thing in codes
LikeLike
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
LikeLike
Hi, could you please give example of XML Instead of JSON . thanks
LikeLike
Nice post.Thank you.
LikeLike
Nice post, could you please give example how to post value for API testing same as above example?
LikeLike
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
}
LikeLike
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.
LikeLike
Hi,
What are you trying parse? Please share the Code.Is that your service URL?
LikeLike
Generally
java.lang.UnsupportedClassVersionError happens because of a higher JDK during compile time and lower JDK during runtime.Please chck the JDK version
LikeLike
We are waiting for next post on — Smart way of Rest API Testing using Selenium Webdriver
LikeLike
Really nice explanation!!
The information that you have provided is very useful. If anyone want to lean more, he/she can visit Selenium Testing
LikeLike
JSONObject obj = new JSONObject(entireResponse ); is wrong as JSON class does not conatin this constructor
LikeLike
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
LikeLike
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
LikeLike
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
LikeLike
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.
LikeLike
Request you to Please post an example of POST request for any Generic Scenario.
Thanks in Advance.
LikeLike
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
LikeLike
Not able to resolve jsobject and jsarray as type
LikeLike
Thanks
LikeLike
How come Selenium comes to picture in the above code , it’s plain Java code
LikeLike
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.
LikeLike
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.
LikeLike
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
LikeLike
Facing the similar issue
LikeLike
Facing same issue.. pls help
LikeLike
Hi, How can we pass API-key through this code when endpoint is not open
Thanks in Advance…..
LikeLike
How to continue to run the automation with same Jsession ID.
LikeLike
Good One … Very helpful.. thanks for sharing
LikeLike
How do i Post multi array json??? using this format
(“/posts”, “{\”token\”:”+passtoken+” , \”id\”:\”49602\”}”, “application/json”)
LikeLike