Table of contents
1.
Introduction
2.
Basic Concepts
3.
About ITestContext
4.
Pass Value From One API to Another 
4.1.
Retrieve Data From an API
4.2.
Pass Data to Another API
5.
Frequently Asked Questions
5.1.
How to convert JSON to string?
5.2.
What are {} and [] used in JSONpath expressions for?
5.3.
Is JSON secure or free from viruses?
5.4.
Which is better, postman or Rest assured?
5.5.
Why is JSON used over XML?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

REST Assured – How to pass value from one API to Another API using TestNG – ITestContext

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this blog, we will learn how to pass value from one API to another using ITestContext of TestNG in REST assured.

introductory image

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.

Basic Concepts

To understand how to pass value from one API to another using ITestContext of TestNG in REST assured, we first need to understand what these terms mean.

The word API stands for Application Programming Interface, and it acts as a messenger that runs back and forth between databases, applications, and devices to deliver data and create the connectivity that puts the world at our fingertips.

api testng itestcontext

TestNG is a testing framework that aims to simplify a wide range of testing tasks, from unit testing to integration testing.
It makes testing more accessible by providing various parameters that help in data handling.

One such parameter is ITestContext. 
ITestContext is passed as a parameter and stores and shares data using the TestNG framework. 
It contains all the information regarding the test to be performed. This is helpful for tests of the same type/class.

To pass value from one API to another using ITestContext of TestNG in REST assured, we pass the output from one API as an input to another API

About ITestContext

As discussed in the above section, ITestContext is used when several tests are stored in the same class. We will use methods provided under ITestContext to store value in a variable and then store it. And then, we will pass value from one API to another using ITestContext of TestNG in REST assured.

SYNTAX:

@Test
public void test(ITestContext context){
	<test values>
}
You can also try this code with Online Java Compiler
Run Code


Methods provided by ITestContext are:

  1. setattribute(attribute name, attribute value) - Sets the value of the passed attribute. It accepts any type of value in the form of key-value pair.
     
  2. getattribute(attribute name) - We get the value of the passed attribute. It returns the attribute's value in the Object type.
     

We will discuss this in detail in the next section with examples.

Pass Value From One API to Another 

In this section, we will learn how to pass value from one API to another using ITestContext of TestNG in REST assured.

We will use the methods under ITestContext as discussed above.

api interaction

We will retrieve data from an API and use this output as input to pass to another API.

Steps guide to pass value from one API to another using ITestContext of TestNG in REST assured:

  1. Chain APIs to perform CRUD operations on member entities.
    (CRUD - create, read, update and delete.)
     
  2. Make a post request to create a member.
     
  3. Retrieve the id property from the response and store it in an integer variable.
     
  4. Make a get request to pull the newly created member using the id property.
     
  5. Make a put request to update the member.

Retrieve Data From an API

The first step to pass value from one API to another using ITestContext of TestNG in REST assured is to create a member.
A member is a term used here to represent the retrieved data from an API. 
We will use the setattribute() method to store the data from an API, and then it can be used to pass to other APIs using the getattribute() method.

For example:

INPUT:

package sharing data;
Import org.testing.ITestContext;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
public class ShareDataUsingITestContext {
	@Test
	public void createBooking(ITestContext context) {
		int bookingId = RestAssured.given().log().all()
						.baseUri("https://gitrepository.file27.com/")
						.basePath("booking")
						.contentType(ContentType.JSON)
						.body("{\r\n" +
							"    \"firstname\" : \"Anchita\",\r\n" +
							"    \"lastname\" : \"Sharma\",\r\n" +
							"    \"totalprice\" : 300,\r\n" +
							"    \"depositpaid\" : false,\r\n" +
							"    \"bookingdates\" : {\r\n" +
							"        \"checkin\" : \"2022-05-10\",\r\n" +
							"        \"checkout\" : \"2022-05-22\"\r\n" +
							"    },\r\n" +
							"    \"complimentary\" : \"Breakfast\"\r\n" +
							"}").when()
						 .post()
						 .then()
						 .log()
						 .all()
						 .extract()
						 .jsonPath()
						  .get("bookingid");
		// Store this data using setattribute() method to use for other tests
		context.setAttribute("bookingId", bookingId);
	}
}
You can also try this code with Online Java Compiler
Run Code


We created a member and set the values inside the member to a variable. This variable will be used to transfer data as input for other APIs to perform tasks.

OUTPUT:

output

output

Pass Data to Another API

In the above section, we learned how to store data from the response of an API.
The next step to pass value from one API to another using ITestContext of TestNG in REST assured is to pass this stored data to another API.
We will use the getattribute() method of ITestContext to pass data.

For example:

INPUT:

package SharingData;
import org.testng.ITestContext;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
public class ShareDataUsingITestContext {
@Test
public void updateBooking(ITestContext context) {
		// Retrieving required data from context
		int bookingId = (int) context.getAttribute("bookingId");
		RestAssured.given().log().all().baseUri("https://gitrepository.file27.com/")
		.basePath("booking/"+bookingId)
		.header("Authorization","Basic YWRtaW46cGFzc3dvcmQxMjM=")
		.contentType(ContentType.JSON)
		.body("{\r\n" +
			"    \"firstname\" : \"Anshit\",\r\n" +
			"    \"lastname\" : \"Singh\",\r\n" +
			"    \"totalprice\" : 600,\r\n" +
			"    \"depositpaid\" : true,\r\n" +
			"    \"bookingdates\" : {\r\n" +
			"        \"checkin\" : \"2022-08-22\",\r\n" +
			"        \"checkout\" : \"2022-09-12\"\r\n" +
			"    },\r\n" +
			"    \"complimentary\" : \"Breakfast\"\r\n" +
			"}")
			.when()
			.put()
			.then()
			.log()
			.all();
	}
}
You can also try this code with Online Java Compiler
Run Code


We used the variable “bookingid” which we created earlier that stores the data from an API. This variable transfers data as input to other APIs to update the values.

OUTPUT:

output

output

We have successfully used the variable created earlier to pass value from one API to another using ITestContext of TestNG in REST assured.

Now it’s time to discuss some FAQs.

Frequently Asked Questions

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.

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

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

Is JSON secure or free from viruses?

JSON can be hijacked and is not completely free from viruses either. The attacker targets a system with access to JSON data. And then can retrieve data from a JSON file.

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.

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. At the same time, XML requires an XML parser.

Conclusion

In this article, we discussed ITestContext in TestNG and how to use it in rest assured. We also learned how to pass value from one API to another using ITestContext of TestNG in REST assured. 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 DSACompetitive ProgrammingJavaScript, 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!

Live masterclass