Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
JSONpath Expression
2.1.
JSONPath Evaluator
2.2.
Writing JSONPath Expressions
3.
Deserialize JSONpath in REST Assured
3.1.
Deserialize JSONpath In REST Assured By JSON Object
3.2.
Deserialize JSONpath In REST Assured By JSON Array
4.
URL Parameters in Rest Assured
5.
Frequently Asked Questions
5.1.
Which is better, postman or Rest assured?
5.2.
Has Rest assured a BDD framework?
5.3.
How to convert JSON to string?
5.4.
Why is JSON used over XML?
5.5.
What are {} and [] used in JSONpath expressions for?
6.
Conclusion
Last Updated: Apr 16, 2024
Easy

Learn to write JSONPath Expressions or JSONPath Syntax and Deserialize it in Rest Assured

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

This article will teach you how to write robust tests in JSONPath expressions in REST assured. We will also learn how to deserialize JSONpath expressions in REST assured.

As we know, testing in Java is more challenging than in languages like Groovy or Ruby. These dynamic languages use fewer lines of code for writing functions. We still use Java because it is faster than these languages. It also provides more stability and usually fewer errors comparatively.

JSONPath expressions in REST assured

REST stands for REpresentational State Transfer. And Rest assured is the Java library. It validates the response of your code in the dynamic languages to the Java domain. You can do this in three simple steps:

  1. Create a request with parameters.
     
  2. Send the request through the HTTP method.
     
  3. Evaluate the response to validate exciting things.

JSONpath Expression

Javascript Object Notation or JSON is a format for storing data.
The query language is the language the user uses to request the database for some data or information.
To retrieve data from a JSON document, we use JSONpath. It is a query language for JSON.
You must learn how to write a perfect JSONpath expression (or syntax) in REST assured to retrieve complex data.

JSON logo

There are a lot of JSONpath expressions in REST assured. Only a few are supported by Rest assured. 
We will learn about all the JSONpath expressions that Rest assured supports.

REST assured uses Groovy Gpath notation of JSONpath expressions in REST assured.

JSONPath Evaluator

Suppose we have a GET query consisting of JSON elements. To retrieve the information, you need to write a JSONpath expression in REST assured.
We will take additional support from the JSONpath evaluator.

JSONpath evaluator

Steps guide:

  1. Paste the GET query in the input.
     
  2. Write a JSONpath expression in REST assured in the “JSON path” box. You can do that in the following ways.
    A. $ symbol - gives all the details from the root node.
    B. $ + “ . ” + array name - gives data in that array.
    C. $ + [‘array name’] - gives data in that array.
    D. $ + [‘array name’] + [*] + .string name - gives all the string values in that array.
    E.  $ + [‘array name’] + [index number] - gives values in that index of the array.
     
  3. Evaluation results will show the retrieved data.

Writing JSONPath Expressions

Before writing the JSONpath expression in REST assured, you must write a few lines of code to add a JSON Object to the JSONpath for retrieving data. 
The code will include the following:

String JSONObject = “{<JSON Object> }”;

\\ Converting JSONobject to JSONpath expression.
JSONPath JSONPath = JSONPath.from(JSONObject);


To include the data, import the JSONpath header file. Inside the curly brackets of “string JSONobject = { }”.
Now you can write JSONPath expressions.

As discussed above, only a few JSONPath expressions are supported by REST assured.
That is as follows:

JSONpath.getstring:

  • JSONpath.getstring(“ [index number].variablename”): This returns the value in that index with the string name as specified.
     
  • JSONpath.getstring(“size()”): This returns the size of the array.
     
  • JSONpath.getstring(“find{it.variablename}”): This finds and then returns its value.
     

JSONpath.getlist:

  • JSONpath.getlist(“variablename”): This will pick variable names from all elements and return the values.
     
  • JSONpath.getlist(“findAll{it.variablename}”): This finds and then returns its value.
     

JSONpath.getJSONObject:

  • JSONpath.getJasonObject(“[index number]”): This returns all values in the element of that index.
     

For example:
We will write a JSONpath expression for the following JSON array.

[{
  "id": 1,
  "firstname": "Anchita",
  "lastname": "Sharma",
  "email": "anchita.sharma@codingninjas.com",
  "gender": "female"
}, {
  "id": 2,
  "firstname": "Anshit",
  "lastname": "Singh",
  "email": "anshitsingh@codingninjas.com",
  "gender": "Male"
}, {
  "id": 3,
  "firstname": "Stuti",
  "lastname": "Jain",
  "email": "stutijain@codingninjas.com",
  "gender": "Female"
}]


INPUT:

package JsonPathSyntax;

import java.io.File;
import io.restassured.path.json.JsonPath;
 
public class SyntaxForJsonArray {

	public static void main(String[] args) {

	String JSONarray=”{[{
  						"id": 1,
  						"firstname": "Anchita",
  						"lastname": "Sharma",
  						"email": "anchita.sharma@codingninjas.com",
  						"gender": "female"
						}, {
  						"id": 2,
  						"firstname": "Anshit",
  						"lastname": "Singh",
  						"email": "anshitsingh@codingninjas.com",
  						"gender": "Male"
						}, {
  						"id": 3,
  						"firstname": "Stuti",
  						"lastname": "Jain",
  						"email": "stutijain@codingninjas.com",
  						"gender": "Female"
					}]}”
	JsonPath jsonPath = JsonPath.from(JSONarray);

	// To get one value using index
	System.out.println("First name of the first employee :"+ jsonPath.getString("[0].firstname"));

	// To get whole indexed element
	System.out.println("All details of first employee : " +jsonPath.getJsonObject("[0]"));

	// To get one value from different JSON objects in the array 
	System.out.println("First name of all employees :" + jsonPath.getList("firstname"));

	// To get the list as of specific group
	System.out.println("First name of all female employees : "+jsonPath.getList("findAll{it.gender == 'Female'}.firstname"));

	// We can get size of array using size()
	System.out.println("Total number of employees : " + jsonPath.getString("size()"));
	}
}


OUTPUT:

output
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Deserialize JSONpath in REST Assured

To serialize means converting a Java object into a JSON object to a JSONPath expression in REST assured. It is vice versa in the case when we deserialize JSONpath in REST assured.
Converting a JSON object into a Java object is termed to Deserialize JSONpath in REST assured. You can do this using JSONPath expressions in REST assured.

Deserialize JSONpath In REST Assured By JSON Object

Follow the steps mentioned in the “Writing JSONPath expressions in REST assured” section above.
Now you’re good to go.

We use .getobject to deserialize JSONpath in REST assured. You can do that in the following two ways:

1) JSONPath.getObject("", stringname.class)  
2) JSONPath.getObject("$", stringname.class) 


Further, in these nodes, we can retrieve data using the .get + variable name of the element.
For example:

INPUT:

package Deserialize;
 
import io.restassured.path.json.JsonPath;
 
public class Deserialize {

	public static void main(String[] args) {

		String jsonObject = "{\r\n" +
							"  \"id\": 1,\r\n" +
							"  \"firstname\": \"Anchita\",\r\n" +
							"  \"lastname\": \"Sharma\",\r\n" +
							"  \"email\": \"anchita.sharma@codingninjas.com\",\r\n" +
							"  \"gender\": \"Female\"\r\n" +
							"}";

		JsonPath jsonPath = JsonPath.from(jsonObject);

		Employee employee = jsonPath.getObject("$", Employee.class);
		System.out.println("Id is      : "+employee.getId());
		System.out.println("First name is : "+employee.getFirstname());
		System.out.println("Last name is  : "+employee.getLastname());
		System.out.println("Email id is   : "+employee.getEmail());
		System.out.println("Gender is  : "+employee.getGender()); 		
	} 		
}


In this example, we have used the “$+stringname” method to deserialize JSON object.

OUTPUT:

output image

Deserialize JSONpath In REST Assured By JSON Array

Follow the steps mentioned in the “Writing JSONPath expressions in REST assured” section above.
Now you’re good to go.

We use .getobject to deserialize JSONpath in REST-assured JSON arrays. You can do that only in one way:

JSONPath.getObject("[index number]", stringname.class) 


This will return all the elements in that index number. It is similar to the example of the deserialization of JSON objects given in the previous section, the only difference is instead of the “$”, we insert the index value in straight brackets[].

Further, in these nodes, we can retrieve data using .get + variablename of the element.

URL Parameters in Rest Assured

Why do we need to parameterize URLs?

It makes it easier to modify the content but it is also essential to ensure no page indexing issues occur.
Parameters are added at the end of an URL.
For example:

https://codingninjas.com/{Coding Ninjas Studiolibrary}


The part inside {} is the URL parameter. It is always inside curly brackets.
You can add URL parameters in two ways:

1. Using PathParam()
The syntax is :

.pathparam(“parameter value”,”parameter value”)


This takes two parameter values: name and value of the parameter.
The parameter name will be replaced by the parameter value during run time.

2. Using inline path parameter
The syntax is :

.get(“URL/{parameter name}”, “parameter value”)


In this method, the value is based on an index.
In case you use both methods together. The Pathparam method will run first. It will set values for the path parameters. The inline method will set the remaining path parameters by their index.
For example:

INPUT:

@Test
public void pathvariable()
{
	RestAssured
		.given()
		.log()
		.all()
		.baseUri("https://repl.it.com/")
		.basePath("{}")
    	.pathParam("path", "createcode")
		.when()
        .get("https://repl.it.com/{Path}/{createcode}", “create”,  5)
		.then()
		.log()
		.all();
}


In this example, “create” will be the value of “Path” at the 0 index and “5” will be the value of “createcode” at the 1st index. This is how the inline method works according to the indexes. 

OUTPUT:

output image
output image

Notice how “Path” is replaced by “createcode” during execution. 

Now it’s time for some FAQs.

Must Read Array of Objects in Java

Frequently Asked Questions

Which is better, postman or Rest assured?

Rest assured is better than the postman. Rest assured, you can reuse code as it is a Java client. Moreover, in postman, we can provide only one data file for each collection, unlike in Rest assured.

Has Rest assured a BDD framework?

Yes. Rest assured is a java library used for testing. It is a behavior-driven-development framework. Such as when and then notations.

How to convert JSON to string?

JSON.stringify() is used for this purpose. The result will be a string. It will follow the JSON notation.

Why is JSON used over XML?

JSON is designed for data interchange. Thus it is faster than XML. Moreover, JSON can be parsed by a javascript function. Whereas XML requires an XML parser.

What are {} and [] used in JSONpath expressions for?

JSONpath expressions in REST assured is a query language for JSON. It uses [] for JSON arrays. And it uses {} for objects in JSONpath expressions in REST assured.

Conclusion

In this article, we discussed various ways to write JSONPath expressions in REST assured, including how to get required data using the JSONpath evaluator and how to deserialize JSONpath in REST assured. We also learned to add URL parameters. 

To learn more about REST assured, refer to the introduction to rest assuredJSON objects in rest assured, and creating JSON objects and arrays.

Please refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. And also, enroll in our courses and refer to the mock test and problems available. Have a look at the interview experiences and interview bundle for placement preparations.

Happy Learning!

Previous article
REST Assured – What is JSONpath and how to create it for simple and nested JSON Objects?
Next article
REST Assured – How to pass value from one API to Another API using TestNG – ITestContext
Live masterclass