Extracting a JSON Response with Rest-Assured


In the earlier post, we studied about Testing GET Requests and their Responses using Rest Assured, before following this tutorial, I would recommend reading the previous one. In this post, we will learn about extracting JSON Response using Rest Assured. Once the response is extracted we will store it into Response class and later various tests can be performed to check whether extracted response is correct.
I would assume that everyone following this tutorial has knowledge of Java and TestNG. If you need help then please follow tutorials on Java and TestNG.

Now let's look at an example where we will search for a particular Railway Station in Mumbai City and print the response.
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import static io.restassured.RestAssured.*;

public class GetJsonResponseTest {

   @BeforeClass
   public void setBaseUri () {

     RestAssured.baseURI = "https://maps.googleapis.com";
   }
   
   @Test
   public void test01()  {
     Response res  = given ().param ("query", "Churchgate Station")
     .param ("key", "Xyz")
     .when()
     .get ("/maps/api/place/textsearch/json")
     .then()
     .contentType(ContentType.JSON)
     .extract().response();


     System.out.println (res.asString ());

   }

}
In setBaseUri method, We are simply setting the default URI  to use in all of our tests. Now when we write out a test that calls an API (as we will do in the next step), we don’t have to type in the full address of the API.

In test01 method, we are using the  given - when - then format. 
We start with given method and specify query and key parameter using the param method then we use the ‘when‘ method and use the ‘get’ method to call ‘Text Search API‘. 

Remember that we set the defaults for the base URI , so the full address of the API that is actually being called here ‘https://maps.googleapis.com/maps/api/place/textsearch/json?query=Churchgate%20Station&key=Xyz‘.

Now we use ‘then‘ part to check the response. We simply add a check ‘contentType(ContentType.JSON)‘ to make sure that the response we get is in JSON format.
Then we extract the response into the Response variable (res) by calling the‘extract().response()‘ methods. Later we convert the response into the string and print it on the console.

Following JSON Response will be printed on console:
{
   "html_attributions" : [],
   "results" : [
      {
         "formatted_address" : "Maharshi Karve Rd, Churchgate, Mumbai, Maharashtra 400020, India",
         "geometry" : {
            "location" : {
               "lat" : 18.9352871,
               "lng" : 72.82723969999999
            },
            "viewport" : {
               "northeast" : {
                  "lat" : 18.93530255,
                  "lng" : 72.82751705
               },
               "southwest" : {
                  "lat" : 18.93528195,
                  "lng" : 72.82714724999998
               }
            }
         },
         "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/train-71.png",
         "id" : "bd620744adf1ac386bca29ae21789e7a3497dd4a",
         "name" : "Churchgate",
         "photos" : [
            {
               "height" : 1750,
               "html_attributions" : [
                  "\u003ca href=\"https://maps.google.com/maps/contrib/100436573426357925098/photos\"\u003eSonu Kushwaha\u003c/a\u003e"
               ],
               "photo_reference" : "CoQBdwAAAMungiqPLNJiKTcsmr3NIsAjt12pD7xQf9WPviqcOGOWH7m_ajPHen0P1ASWBIwDGVNx2ZM4A80YaAoxHaMxH9w468ncaj91x-Xyn7HpVGWpbXoeomp0kkJK45hpgqOv6qiP0JVfeYLnmb3JDDTz95EfLH-CAm9CygwSlzxotCYXEhDQk_Y0EFeLkQKmUbYwnxVPGhRqb8GvTHiQX_rVseJdSuBhLofljA",
               "width" : 2498
            }
         ],
         "place_id" : "ChIJ9RNjZufR5zsRd6X3LdEWiZ0",
         "rating" : 4.4,
         "reference" : "CmRSAAAAkHys22E9AK8z5XT0ptIJrJ-6y7yoC4_p3VRR5WiTqtC11f5X19exahmuP19zWNi-7Fp8e0zPlMCKSsmlya4vzcDEor5HKc47pvS-Weu-ijn8QF8jpsgEqf3DLN3D3430EhCjcOdmMJQog54lpAYcOK9UGhTkXwmmAakSjs6mNfS9ZetiJn_QhQ",
         "types" : [
            "train_station",
            "transit_station",
            "point_of_interest",
            "establishment"
         ]
      }
   ],
   "status" : "OK"
}

We can view the JSON Response in UI form at the following site:
JSON Viewer . 
Copy and paste the response in text tab and view it in Viewer tab.




We know have above JSON as a String and we can use Rest-Assured to do the testing. A basic test would be to check the formatted_address that is returned by the API call. We could do this by specifying JSON path in the path method.

JSON Path is an XPath like query language for JSON that enables you to select nodes in a JSON document. The Retrieve Attributes with JSON Path filter enables you to retrieve specified message attributes from a JSON message using JSON Path expressions.

If we want to get formatted_address from above JSON Response then the JSON path will be $.results[0].formatted_address





To represent the head of JSON we use $ sign and “.” means next node and subsequent “.” may mean next node.

$.results[0].geometry.location.lat - Example of getting latitude
$.results[0].types[0] - Example to get the first type i.e. train_station

JSON path can be tested at following site:
JSON Path Tester
More information on JSON path can be found at following link:
JSON Path Explanation


Let's have a look at the following example which explains the same.
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import static com.jayway.restassured.RestAssured.*;

import com.jayway.restassured.RestAssured;
import com.jayway.restassured.http.ContentType;
import com.jayway.restassured.response.Response;

public class GetRequestTest {

  @BeforeClass
  public void setBaseUri () {

    RestAssured.baseURI = "https://maps.googleapis.com";
  }

  @Test
  public void testResult ()  {
    Response res  =given ().param ("query", "Churchgate Station")
    .param ("key", "Xyz")
    .when()
    .get ("/maps/api/place/textsearch/json").
    .then()
    .contentType(ContentType.JSON)
    .extract().
    .path ("results[0].formatted_address");
    
    Assert.assertEquals (res, "Maharshi Karve Rd, Churchgate, Mumbai, Maharashtra 400020");
    
  }
  
}

The above example is same the previous example that we have learned the only difference is that we have used path method in which we have passed the JSON path to extract the formatted_address from the response.

The response is stored in Response variable res and then we have asserted the response using TestNG assertEquals method, which will mark the test case as passed, in this case.

In the next post, we will learn to Install and Configure API Server on the local system.

Comments

Popular posts from this blog

Extracting an XML Response with Rest-Assured