Rest–Assured is a Java-based library that is used to test RESTful Web Services.
Postman is an API platform for building and using APIs. It simplifies each step of the API lifecycle and streamlines collaboration, so you can create better APIs—faster.
Last Updated On
In this tutorial, we will create a GET request in Postman and see how to execute it.
Table of Contents
A GET request gets the information from the server. When you make the GET request on the server, then the server responds to the request.
GET requests will not affect any data on the server. This means, there is no creation, updation, addition, or deletion of data on the server when you are making a GET request.
We will use the following URL for this Postman tutorial.
http://dummy.restapiexample.com/api/v1/employees
To create the first GET request in Postman, follow the following steps:
Step 1: Create a Collection, click on Collections, and then click on the “+” plus button.

Step 2: Provide a name to the collection – “API Testing”.

Step 3: To create a new request, click on “Add a request”, if it is a new Collection. Otherwise, click on the 3 dots and select “Add request”.

Step 4: Once you create a new request, then you will get the following window:

Step 5: Enter the “name” in the request. Here, the name is “GET Demo”.

Step 5: Enter the “URL” in the address bar.

Step 6: Now, select the “GET” request from the list of request methods.

Send the Request
Step 7: Press the “Send” button.

Step 8: Once you press the send button, you will get the response from the server. Make sure you have a proper internet connection; otherwise, you will not get a response.

Status
You can check the status code. Here, we got the status code 200, which means we got a successful response to the request.

Body
In the Body tab of the response box, we have multiple options to see the response in a different format.

Format Type
Each request has a defined response to it as defined by the Content-Type header. That response can be in any format. Such as in the above example, we have JSON code file.
Below are the various format type present in Postman.
XML

HTML

Text

Headers
Headers are the extra information that is transferred to the server or the client. In Postman, headers will show like key-value pairs under the headers tab. Click on the Headers link as shown in the below image:

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
Last Modified Date
In this tutorial, we will integrate JMeter with Maven to support CI/CD.
Maven and jmeter-maven-plugin make it easy to integrate performance tests with CI/CD tools & technologies such as Jenkins/Jenkinsfiles or Azure/Azure pipelines and cloud build agents. It also helps to run your tests with different versions of JMeter.
Table of Contents
This is a Maven 3 plugin that allows you to run JMeter tests as part of the build.

A new project will be created with pom.xml as shown below

pom.xml is our Maven project main file, which contains all the necessary information and dependencies bound to our project.
Compile the project by using the below command
mvn clean compile
The compilation fails with the errors as shown below:

Add the Maven Compiler plugin in the build section of the pom.xml.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.11.0</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</build>
Rerun compile command and this time the build is successful.

Add the JMeter Maven plugin to the build section of the pom.xml.
<plugin>
<groupId>com.lazerycode.jmeter</groupId>
<artifactId>jmeter-maven-plugin</artifactId>
<version>3.6.0</version>
<executions>
<!-- Generate JMeter configuration -->
<execution>
<id>configuration</id>
<goals>
<goal>configure</goal>
</goals>
</execution>
<!-- Run JMeter tests -->
<execution>
<id>jmeter-tests</id>
<goals>
<goal>jmeter</goal>
</goals>
</execution>
<!-- Fail build on errors in test -->
<execution>
<id>jmeter-check-results</id>
<goals>
<goal>results</goal>
</goals>
</execution>
</executions>
<configuration>
<generateReports>true</generateReports>
</configuration>
</plugin>
Create a new directory within src/test with the name jmeter.

Place the JMeter script(.jmx) file in src/test/jmeter. The steps to create a Test Plan in JMeter are mentioned at the end of the page.

Go to your project directory and run the following command in the command line:
mvn clean verify
The test execution is displayed in the command line as shown below:

The test ran successfully! The results are located at /target/jmeter/reports. You will find an HTML report named “Index.html”:

Right-click on the Index.html and select Open In->Browser->Chrome (any browser of your wish).
This report provides the following metrics:
In the Dashboard of the report;

A Statistics table providing in one table a summary of all metrics per transaction including 3 configurable percentiles:

An error table providing a summary of all errors and their proportion in the total requests

A Top 5 Errors by Sampler table providing for every Sampler (excluding Transaction Controller by default) the top 5 Errors:

You can see that there are a lot of other types of reports too. You should explore these reports.

Sample Request
{
"name": "Test",
"job": "JMeter"
}
Sample Response
{
"name":"Test",
"job":"JMeter",
"id":"955",
"createdAt":"2023-07-03T15:46:18.038Z"
}

In the Thread Group control panel, enter Thread Properties as follows: We will take an example of row no 5
Number of Threads: 5 – Number of users connects to the target website
Loop Count: Infinite – Number of times to execute testing
Ramp-Up Period: 5 – It tells JMeter how long to delay before starting the next user. For example, if we have 5 users and a 5 -second Ramp-Up period, then the delay between starting users would be 1 second (5 seconds /5 users).
Duration – 2 sec

The JMeter element used here is HTTP Request Sampler. In HTTP Request Control Panel, the Path field indicates which URL request you want to send
2.1 Add HTTP Request Sampler
To add: Right-click on Thread Group and select: Add -> Sampler -> HTTP Request

The below-mentioned are the values used in HTTP Request to perform the test

2.2 Add HTTP Head Manager
The Header Manager lets you add or override HTTP request headers like can add Accept-Encoding, Accept, Cache-Control
To add: Right-click on Thread Group and select: Add -> Config Element -> HTTP Read Manager

The below-mentioned are the values used in Http Request to perform the test
Content-type = application/json

Listeners – They show the results of the test execution. They can show results in a different format such as a tree, table, graph, or log file
We are adding the View Result Tree listener
View Result Tree – View Result Tree shows the results of the user request in basic HTML format
To add: Right-click on Test Plan, Add -> Listener -> View Result Tree

Aggregate Report
It is almost the same as Summary Report except Aggregate Report gives a few more parameters like, “Median”, “90% Line”, “95% Line” and “99% Line”.
To add: Right Click on Thread Group > Add > Listener > Aggregate Report

To Save: Click File Select -> Save Test Plan as ->Give the name of the Test Plan (POST_LoadDemo.jmx). It will be saved in .jmx format.

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
Last Modified Date
JMeter supports dashboard report generation to get graphs and statistics from a test plan. In this tutorial, we will explain how to generate JMeter HTML Report.
The dashboard generator is a modular extension of JMeter. Its default behaviour is to read and process samples from CSV files to generate HTML files containing graph views. It can generate the report at the end of a load test or on demand.
There are 2 ways to generate HTML Report
Sample Request
{
"name": "Test",
"job": "JMeter"
}
Sample Response
{
"name":"Test",
"job":"JMeter",
"id":"955",
"createdAt":"2023-07-03T15:46:18.038Z"
}

In the Thread Group control panel, enter Thread Properties as follows: We will take an example of row no 5
Number of Threads: 5 – Number of users connects to the target website
Loop Count: 5 – Number of times to execute testing
Ramp-Up Period: 5 – It tells JMeter how long to delay before starting the next user. For example, if we have 5 users and a 5 -second Ramp-Up period, then the delay between starting users would be 1 second (5 seconds /5 users).

The JMeter element used here is HTTP Request Sampler. In HTTP Request Control Panel, the Path field indicates which URL request you want to send
2.1 Add HTTP Request Sampler
To add: Right-click on Thread Group and select: Add -> Sampler -> HTTP Request

The below-mentioned are the values used in HTTP Request to perform the test

2.2 Add HTTP Head Manager
The Header Manager lets you add or override HTTP request headers like can add Accept-Encoding, Accept, Cache-Control
To add: Right-click on Thread Group and select: Add -> Config Element -> HTTP Read Manager
The below-mentioned are the values used in Http Request to perform the test
Content-type = application/json
accept – application/json

Listeners – They show the results of the test execution. They can show results in a different format such as a tree, table, graph, or log file
We are adding the View Result Tree listener
View Result Tree – View Result Tree shows the results of the user request in basic HTML format
To add: Right-click on Test Plan, Add -> Listener -> View Result Tree

Aggregate Report
It is almost the same as Summary Report except Aggregate Report gives a few more parameters like, “Median”, “90% Line”, “95% Line” and “99% Line”.
To add: Right Click on Thread Group > Add > Listener > Aggregate Report

To Save: Click File Select -> Save Test Plan as ->Give the name of the Test Plan. It will be saved in .jmx format.

The below image shows that the test is saved in Documents with the name POST_Load.jmx.

Open the command prompt and go into JMeter’s bin folder.
cd C:\Users\Vibha\Documents\apache-jmeter-5.6\apache-jmeter-5.6\bin
Enter the following command:
jmeter -n -t <test JMX file> -l <test log file> -e -o <Path to output folder>
This is the command used in the script:
jmeter -n -t C:\Users\Vibha\Documents\apache-jmeter-5.6\apache-jmeter-5.6\POST_Load.jmx -l C:\Users\Vibha\Documents\JMeterResult\result1.csv -e -o C:\Users\Vibha\Documents\JMeterResult\Report
Below is the detail about the commands used in the execution.
-n: This specifies JMeter is to run in cli mode
-t: [name of JMX file that contains the Test Plan]
-l: [name of JTL file to log sample results to]
–e: generate report dashboard after load test
-o: output folder where to generate the report dashboard after the load test. The folder must not exist or be empty
The test execution is displayed in the command line as shown below:

The result1.csv is saved as mentioned in the above command in the JMeterResult folder present in Documents:

Go to the Report Folder. You can find the generated HTML files in the given report path.

This report provides the following metrics:
In the Dashboard of the report;

A Statistics table providing in one table a summary of all metrics per transaction including 3 configurable percentiles:

An error table providing a summary of all errors and their proportion in the total requests

A Top 5 Errors by Sampler table providing for every Sampler (excluding Transaction Controller by default) the top 5 Errors:

You can see that there are a lot of other types of reports too. You should explore these reports.

Imagine, we have run the tests from JMeter GUI. Mention the path where we want to save the result file in the Filename option of one of the listeners.

Run the tests, and we can see that the result is generated.

Now, let us create a Report.
jmeter -g C:\Users\Vibha\Documents\JMeterResult\Result2.csv -o C:\Users\Vibha\Documents\JMeterResult\Report1
We can see that a new folder – Report1 is created.

Go inside the Report1 folder and see that the Index.html report is generated.

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
In this tutorial, we will explain how to run tests in JMeter in non-GUI mode (Command Line mode).
The JMeterGUI’s inability to handle huge loads and excessive resource consumption risks overloading the server, which would give you inaccurate test results information. Additionally, the less load you can generate throughout your tests, the more resource-intensive the server is.
Sample Request
{
"name": "Test",
"job": "JMeter"
}
Sample Response
{
"name":"Test",
"job":"JMeter",
"id":"955",
"createdAt":"2023-07-03T15:46:18.038Z"
}

In the Thread Group control panel, enter Thread Properties as follows: We will take an example of row no 5
Number of Threads: 5 – Number of users connects to the target website
Loop Count: 5 – Number of times to execute testing
Ramp-Up Period: 5 – It tells JMeter how long to delay before starting the next user. For example, if we have 5 users and a 5 -second Ramp-Up period, then the delay between starting users would be 1 second (5 seconds /5 users).

The JMeter element used here is HTTP Request Sampler. In HTTP Request Control Panel, the Path field indicates which URL request you want to send
2.1 Add HTTP Request Sampler
To add: Right-click on Thread Group and select: Add -> Sampler -> HTTP Request

The below-mentioned are the values used in HTTP Request to perform the test

2.2 Add HTTP Head Manager
The Header Manager lets you add or override HTTP request headers like can add Accept-Encoding, Accept, Cache-Control
To add: Right-click on Thread Group and select: Add -> Config Element -> HTTP Read Manager
The below-mentioned are the values used in Http Request to perform the test
Content-type = application/json
accept – application/json

Listeners – They show the results of the test execution. They can show results in a different format such as a tree, table, graph, or log file
We are adding the View Result Tree listener
View Result Tree – View Result Tree shows the results of the user request in basic HTML format
To add: Right-click on Test Plan, Add -> Listener -> View Result Tree

Aggregate Report
It is almost the same as Summary Report except Aggregate Report gives a few more parameters like, “Median”, “90% Line”, “95% Line” and “99% Line”.
To add: Right Click on Thread Group > Add > Listener > Aggregate Report

To Save: Click File Select -> Save Test Plan as ->Give the name of the Test Plan. It will be saved in .jmx format.

The below image shows that the test is saved in Documents with the name POST_Load.jmx.

Open the command prompt and go into JMeter’s bin folder.
cd C:\Users\Vibha\Documents\apache-jmeter-5.6\apache-jmeter-5.6\bin
Enter the following command:
jmeter -n –t test.jmx -l testresults.jtl
This is the command used in the script:
jmeter -n -t C:\Users\Vibha\Documents\apache-jmeter-5.6\apache-jmeter-5.6\POST_Load.jmx -l C:\Users\Vibha\Documents\JMeterResult\result.jtl
Below is the detail about the commands used in the execution.
-n: This specifies JMeter is to run in cli mode
-t: [name of JMX file that contains the Test Plan]
-l: [name of JTL file to log sample results to]
The test execution is displayed in the command line as shown below:

The result.jtl is saved as mentioned in the above command in the JMeterResult folder present in Documents:

Let us open the result.jtl file.

It is very difficult to understand the result in this format. So, open JMeter in GUI mode.
Mention the location of the file in the Filename of the “View Results Tree” listener and hit enter. We can see the result now.

Click on Response data and Response Header to view other information about Response.

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
Last Updated On
In this article, we will discuss in detail how we can perform API testing in Robot Framework.
Table of Contents
Please refer to this tutorial to install Robot Framework – How to install and setup Robot Framework for Python.
RequestLibrary is a Robot Framework library aimed to provide HTTP API testing functionalities by wrapping the well-known Python Requests Library.
Step 1.1 – Open PyCharm and create a new project. Go to File and select New Project from the main menu.

Step 1.2 – Choose the project location. Click the “Browse” button next to the Location field and specify the directory for your project.
Deselect the Create a main.py welcome script checkbox because you will create a new Python file for this tutorial.

Click on the “Create” Button.
Step 1.3 – A new dialog appears asking to open the project using any one of the given options. I have selected New Window as I like to have separate windows for each project.

Below is the image of the new project created in PyCharms.

To install RequestLibrary, you need to use the below command:
pip install robotframework-requests

Go to File->Settings ->Project:RobotFramework_Demo ->Python Interpreter.
Click on the “+” sign and enter pabot in the search bar. It will show a list of packages. Select the “robotframework-requests” package and click on the “Install Package”.

Once the package is installed, we will see the message that the package is installed successfully.

Once the package is installed, it can be seen under the package list as shown below:

Right-Click on the project, select New->Directory, and provide the name as API_Tests

Below is the image of the new directory.

Right-click on the new directory and select New File and provide the name as API_Demo.robot as shown below:


The corresponding API Test in Robot Framework.
*** Settings ***
Library RequestsLibrary
Library Collections
*** Variables ***
${base_url} https://reqres.in/api/users
${page_id} 2
*** Test Cases ***
Quick Get Request Test
${response}= GET ${base_url} params=page=${page_id} expected_status=200
log ${response.json()}
Should Be Equal As Strings 6 ${response.json()}[per_page]
Should Be Equal As Strings 12 ${response.json()}[total]
Should Be Equal As Strings 7 ${response.json()}[data][0][id]
The corresponding log of this request is

${response}= We are saving the response of the GET operation in the ${response} variable.
The response is logged in the log by using the below command:
log ${response.json()}

The corresponding API Test in Robot Framework.
*** Settings ***
Library RequestsLibrary
Library Collections
*** Variables ***
${base_url} https://reqres.in/api/users
${page_id} 2
${expectedname} test
${expectedjob} team leader
*** Test Cases ***
Quick POST Request Test
&{req_body}= Create Dictionary name=test job=team leader
${response}= POST ${base_url} json=${req_body} expected_status=201
log ${response.json()}
Dictionary Should Contain Key ${response.json()} id
${name}= Get From Dictionary ${response.json()} name
Should Be Equal As Strings ${expectedname} ${name}
${job}= Get From Dictionary ${response.json()} job
Should Be Equal As Strings ${expectedjob} ${job}
The corresponding log of this request is

1.Create Dictionary – This keyword is used from BuiltIn Library. It creates and returns a dictionary based on the given Items. Items are typically given using the key=value syntax.
2. Dictionary should contain key – This keyword is used from Collections library. It is used to verify if the specified key is present in the dictionary.
3. Get From Dictionary – This keyword is used from the Collections library. It is used to return a value from the given dictionary based on the given key. Here, it is used to check the values of the key name and job.

The corresponding API Test in Robot Framework.
*** Settings ***
Library RequestsLibrary
Library Collections
*** Variables ***
${base_url} https://reqres.in/api/users
${updated_expectedname} update_test
${updated_expectedjob} resident
*** Test Cases ***
Quick PUT Request Test
&{req_body}= Create Dictionary name=update_test job=resident
${response}= PUT ${base_url}+/2 json=${req_body} expected_status=200
log ${response.json()}
Dictionary Should Contain Key ${response.json()} name
${name}= Get From Dictionary ${response.json()} name
Should Be Equal As Strings ${updated_expectedname} ${name}
Dictionary Should Contain Key ${response.json()} job
${job}= Get From Dictionary ${response.json()} job
Should Be Equal As Strings ${updated_expectedjob} ${job}
The corresponding log of this request is


The corresponding API Test in Robot Framework.
*** Settings ***
Library RequestsLibrary
*** Variables ***
${base_url} https://reqres.in/api/users
*** Test Cases ***
Quick DELETE Request Test
${delete_resp}= DELETE ${base_url}+/2 expected_status=204
The corresponding log of this request is

The complete program looks like

We need the below command to run the Robot Framework script.
robot API_DEMO.robot
The output of the above program is

We have the test case passed. The Robot Framework generates log.html, output.xml, and report.html by default.
Let us now see the report and log details.
Right-click on report.html. Select Open In->Browser->Chrome(any browser of your wish).
The Report generated by the framework is shown below:

Robot Framework has multiple log levels that control what is shown in the automatically generated log file. The default Robot Framework log level is INFO.
Right-click on log.html. Select Open In->Browser->Chrome(any browser of your wish).

That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
Additional Tutorials
Last Updated On
This tutorial focuses on the testing of a REST API (with JSON payload). We will use Jackson API to serialize the request.
It is suggested to go through these tutorials to understand about creating a JSON Object Payload using POJO (Plain Old Java Object).
How to create JSON Object Payload using POJO – Jackson API
How to create JSON Array Payload using POJO – Jackson API
How to create Nested JSON Object using POJO – Jackson API
To start with, we need to add Jackson Maven’s Dependency to the POM. Always add the latest version of Jackson dependency to your project.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.2</version>
</dependency>
The complete POM.xml will look like this, as shown below:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>RestAssured_JUnit4_Demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<rest-assured.version>5.3.0</rest-assured.version>
<junit.version>4.13.2</junit.version>
<jackson.version>2.17.2</jackson.version>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<!-- Rest-Assured Dependency -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
<!-- JUnit4 Dependency -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- Jackson Dependency -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- Hamcrest Dependency -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
This dependency will also transitively add the following libraries to the classpath:
In the below example, let us assume that we need to create a new Employee (POST Request). To start with, we need to create a POJO class of the JSON payload (EmployeeDetails). This POJO class should contain the data members corresponding to the JSON nodes and their corresponding getter and setter methods.
public class EmployeeDetails {
// private variables or data members of pojo class
private String name;
private double salary;
private int age;
// Getter and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Now that we have our POJO class, we can start writing some REST Assured Serialization tests!
Let’s start with REST Assured Serialization with JSON. I want to send a POST request to my EmployeeDetails API that will add a new Employee to the database. I will send a POJO of the employee in the request body. This is what the code looks like in the test class:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.restassured.http.ContentType;
import org.junit.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class EmployeeTests {
@Test
public void createEmployee() {
// Create an object of POJO class
EmployeeDetails emp = new EmployeeDetails();
emp.setName("Vibha");
emp.setSalary(75000);
emp.setAge(30);
// Converting a Java class object to a JSON payload as string
ObjectMapper mapper = new ObjectMapper();
String employeePrettyJson = null;
try {
employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println("Request");
System.out.println(employeePrettyJson);
System.out.println("=========================================");
System.out.println("Response");
// GIVEN
given().baseUri("https://dummy.restapiexample.com/api").contentType(ContentType.JSON).body(emp)
// WHEN
.when().post("/v1/create")
// THEN
.then().assertThat().statusCode(200).body("data.name", equalTo("Vibha"))
.body("message", equalTo("Successfully! Record has been added.")).log().body();
}
}
The output of the above program is

If you want to see the structure of the Request, then add the below in the test code.
ObjectMapper mapper = new ObjectMapper();
String employeePrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
System.out.println(employeePrettyJson);
REST Assured Serialization with Jackson handled all the serialization work for us. Great! See, this has become so simple with the help of Jackson API.
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
Last Updated On
In the previous tutorial, I explained the creation of JSON Object using POJO. In this tutorial, will create a JSON Array Payload using POJO.
To learn about POJO, please refer to this tutorial.
You can refer to these tutorials to understand various ways of using Jackson API
Serialization – How to create JSON Payload from Java Object – Jackson API
How to create JSON Array Payload using POJO – Jackson API
How to create Nested JSON Object using POJO – Jackson API
Serialization – How to convert Map to JSON string using Jackson API
JSON Array is a collection of JSON Objects. In the below example, will create a list of employees.
The sample JSON Array structure looks like the image as shown below:-
{
"firstName" : "Vibha",
"lastName" : "Singh",
"age" : 30,
"salary" : 75000.0,
"designation" : "Manager",
"contactNumber" : "+919999988822",
"emailId" : "abc@test.com"
"firstName" : "Neha",
"lastName" : "Verma",
"age" : 25,
"salary" : 60000.0,
"designation" : "Lead",
"contactNumber" : "+914442266221",
"emailId" : "xyz@test.com"
"firstName" : "Rajesh",
"lastName" : "Gupta",
"age" : 20,
"salary" : 40000.0,
"designation" : "Intern",
"contactNumber" : "+919933384422",
"emailId" : "pqr@test.com"
}
We need to create an Employee class that contains private data members and the corresponding getter and setter methods of these data members.
Below is an Employee Class with private data members, as well as the corresponding getter and setter methods of these data members. Every IDE provides a shortcut to create these getter and setter methods.
public class Employee {
// private variables or data members of POJO class
private String firstName;
private String lastName;
private int age;
private double salary;
private String designation;
private String contactNumber;
private String emailId;
// Getter and setter methods
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
}
Serialization – Serialization is a process where you convert an Instance of a Class (Object of a class) into a Byte Stream. Here, we are converting Employee class object to JSON Array representation or Object.
Deserialization – It is the reverse of serializing. In this process, we will read the Serialized byte stream from the file and convert it back into the Class instance representation. Here, we are converting a JSON Array to an Employee class object.
We are using Jackson API for Serialization and Deserialization. So, add the Jackson dependency to the project.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>
Below is the class where we will assign values to the data members by using getter methods (Serialization).
public class EmployeeArrayTest {
@Test
public void createEmployeeArray() {
Employee emp1 = new Employee();
emp1.setFirstName("Vibha");
emp1.setLastName("Singh");
emp1.setAge(30);
emp1.setSalary(75000);
emp1.setDesignation("Manager");
emp1.setContactNumber("+919999988822");
emp1.setEmailId("abc@test.com");
Employee emp2 = new Employee();
emp2.setFirstName("Neha");
emp2.setLastName("Verms");
emp2.setAge(35);
emp2.setSalary(60000);
emp2.setDesignation("Lead");
emp2.setContactNumber("+914442266221");
emp2.setEmailId("xyz@test.com");
Employee emp3 = new Employee();
emp3.setFirstName("Rajesh");
emp3.setLastName("Gupta");
emp3.setAge(20);
emp3.setSalary(40000);
emp3.setDesignation("Intern");
emp3.setContactNumber("+919933384422");
emp3.setEmailId("pqr@test.com");
// Creating a List of Employees
List<Employee> employeeList = new ArrayList<Employee>();
employeeList.add(emp1);
employeeList.add(emp2);
employeeList.add(emp3);
// Converting a Java class object to a JSON Array Payload as string
ObjectMapper mapper = new ObjectMapper();
try {
String allEmployeeJson = mapper.writeValueAsString(employeeList);
String employeeListPrettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employeeList);
System.out.println(allEmployeeJson);
System.out.println(employeeListPrettyJson);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
The output of the above program is

ObjectMapper is imported from:-
import com.fasterxml.jackson.databind.ObjectMapper;
In the below example, we are deserializing the JSON Array Payload to Java objects.
@Test
public void getEmployeeArray() {
Employee emp1 = new Employee();
emp1.setFirstName("Vibha");
emp1.setLastName("Singh");
emp1.setAge(30);
emp1.setSalary(75000);
emp1.setDesignation("Manager");
emp1.setContactNumber("+919999988822");
emp1.setEmailId("abc@test.com");
Employee emp2 = new Employee();
emp2.setFirstName("Neha");
emp2.setLastName("Verms");
emp2.setAge(35);
emp2.setSalary(60000);
emp2.setDesignation("Lead");
emp2.setContactNumber("+914442266221");
emp2.setEmailId("xyz@test.com");
Employee emp3 = new Employee();
emp3.setFirstName("Rajesh");
emp3.setLastName("Gupta");
emp3.setAge(20);
emp3.setSalary(40000);
emp3.setDesignation("Intern");
emp3.setContactNumber("+919933384422");
emp3.setEmailId("pqr@test.com");
// Creating a List of Employees
List<Employee> employeeList = new ArrayList<Employee>();
employeeList.add(emp1);
employeeList.add(emp2);
employeeList.add(emp3);
// Converting a Java class object to a JSON Array Payload as string
ObjectMapper mapper = new ObjectMapper();
String allEmployeeJson = null;
try {
allEmployeeJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(employeeList);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
List<Employee> allEmployeeDetails = null;
try {
allEmployeeDetails = mapper.readValue(allEmployeeJson, new TypeReference<List<Employee>>() {
});
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
for (Employee emp : allEmployeeDetails) {
System.out.println("===================================");
System.out.println("First Name of employee : " + emp.getFirstName());
System.out.println("Last Name of employee : " + emp.getLastName());
System.out.println("Age of employee : " + emp.getAge());
System.out.println("Salary of employee : " + emp.getSalary());
System.out.println("Designation of employee : " + emp.getDesignation());
System.out.println("Contact Number of employee : " + emp.getContactNumber());
System.out.println("EmailId of employee : " + emp.getEmailId());
}
}
The output of the above program is

If you want to read the data from a file placed on Desktop, below is the sample code for the same.
@Test
public void readArrayJsonFromFile() throws IOException {
ObjectMapper mapper = new ObjectMapper();
// Converting Employee json string to Employee class object
List<Employee> allEmployeeDetails = null;
try {
allEmployeeDetails = mapper.readValue(new File(
"C:\\Users\\Vibha\\Desktop\\EmployeeList.json"),
new TypeReference<List<Employee>>() {
});
} catch (StreamReadException e) {
e.printStackTrace();
} catch (DatabindException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for (Employee emp : allEmployeeDetails) {
System.out.println("######################################");
System.out.println("First Name of employee : " + emp.getFirstName());
System.out.println("Last Name of employee : " + emp.getLastName());
System.out.println("Age of employee : " + emp.getAge());
System.out.println("Salary of employee : " + emp.getSalary());
System.out.println("Designation of employee : " + emp.getDesignation());
System.out.println("Contact Number of employee : " + emp.getContactNumber());
System.out.println("EmailId of employee : " + emp.getEmailId());
}
}
The output of the above program is

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
Last Updated On
In this tutorial, I will explain how can we extract the body from JSON Response in Rest Assured. This is needed for the assertion of tests. In the previous tutorial, I explained various types of Assertions can be done on JSON Request using Hamcrest.
JsonPath is available at the Central Maven Repository. Maven users add this to the POM.
<!-- https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path -->
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.9.0</version>
</dependency>
If the project is Gradle, add the below dependency in build.gradle.
testImplementation 'com.jayway.jsonpath:json-path:2.6.0'
JsonPath expressions can use the dot–notation.
$.store.book[0].title
or the bracket–notation
$['store']['book'][0]['title']
Below are the most commonly used expressions.
| Expression | Description |
| $ | The root object or array. |
| .property | Selects the specified property in a parent object. |
| [‘property’] | Selects the specified property in a parent object. Be sure to put single quotes around the property name.Tip: Use this notation if the property name contains special characters such as spaces, or begins with a character other than A..Za..z_. |
| [n] | Selects the n-th element from an array. Indexes are 0-based. |
| [index1,index2,…] | Selects array elements with the specified indexes. Returns a list. |
| ..property | Recursive descent: Searches for the specified property name recursively and returns an array of all values with this property name. Always returns a list, even if just one property is found. |
| * | Wildcard selects all elements in an object or an array, regardless of their names or indexes. |
| [start:end] [start:] | Selects array elements from the start index and up to, but not including, end index. If end is omitted, selects all elements from start until the end of the array. Returns a list. |
| [:n] | Selects the first n elements of the array. Returns a list. |
| [-n:] | Selects the last n elements of the array. Returns a list. |
| [?(expression)] | Selects all elements in an object or array that match the specified filter. Returns a list. |
| [(expression)] | Script expressions can be used instead of explicit property names or indexes. An example is [(@.length-1)] which selects the last item in an array. Here, length refers to the length of the current array rather than a JSON field named length. |
| @ | Used in filter expressions to refer to the current node being processed. |
Below is the sample JSON which I am using for extraction examples. I have saved this file in resources/Payloads as test.json.
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
To extract all books present in the store:-
String allBooks = JsonPath.read(jsonString, "$..*").toString();
System.out.println("--------------- All books in the store --------------");
System.out.println(allBooks);
The complete program looks like as shown below:
import com.jayway.jsonpath.JsonPath;
public class JsonPath_Demo {
public static void main(String args[]) {
String jsonString = new String(Files.readAllBytes(Paths.get("src/test/resources/Payloads/test.json")));
String allBooks = JsonPath.read(jsonString, "$..*").toString();
System.out.println("--------------- All books in the store --------------");
System.out.println(allBooks);
}
}
The output of the above program is

Below are examples that show how to extract different nodes from a JSON Body. I have used the above JSON Body for these examples.
// All bicycles in the store
String allBicycles = JsonPath.read(jsonString, "$..bicycle").toString();
System.out.println("--------------- All bicycles in the store ---------------");
System.out.println(allBicycles);
// The number of books
String noOfBooks = JsonPath.read(jsonString, "$..book.length()").toString();
System.out.println("--------------- The number of books ---------------");
System.out.println(noOfBooks);
// The authors of all books
String authors = JsonPath.read(jsonString, "$.store.book[*].author").toString();
System.out.println("--------------- Author of all Books ---------------");
System.out.println(authors);
// All authors
String allAuthors = JsonPath.read(jsonString, "$..author").toString();
System.out.println("--------------- All Authors ---------------");
System.out.println(allAuthors);
// All details of the store
String store = JsonPath.read(jsonString, "$.store.*").toString();
System.out.println("--------------- All details of the store ---------------");
System.out.println(store);
// Price of store
String storePrice = JsonPath.read(jsonString, "$.store..price").toString();
System.out.println("--------------- price of store ---------------");
System.out.println(storePrice);
The output of the above program is

Below are the examples where I have extracted specific book (nodes) from the JSON body.
// Third book
String thirdBook = JsonPath.read(jsonString, "$..book[2]").toString();
System.out.println("--------------- third book ---------------");
System.out.println(thirdBook);
// first Last Book
String firstLastBook = JsonPath.read(jsonString, "$..book[-1]").toString();
System.out.println("--------------- first Last Book ---------------");
System.out.println(firstLastBook);
// first two Books
String firstTwoBooks = JsonPath.read(jsonString, "$..book[0,1]").toString();
System.out.println("--------------- first Two Books ---------------");
System.out.println(firstTwoBooks);
// books from index 0 (inclusive) until index 2 (exclusive)
String booksRange = JsonPath.read(jsonString, "$..book[:2]").toString();
System.out.println("--------------- books from index 0 (inclusive) until index 2 (exclusive) ---------------");
System.out.println(booksRange);
// All books from index 1 (inclusive) until index 2 (exclusive)
String booksRange1 = JsonPath.read(jsonString, "$..book[1:2]").toString();
System.out.println("------------ All books from index 1 (inclusive) until index 2 (exclusive) -----------");
System.out.println(booksRange1);
// Book number one from tail
String bottomBook = JsonPath.read(jsonString, "$..book[1:]").toString();
System.out.println("--------------- Book number one from tail ---------------");
System.out.println(bottomBook);
The output of the above program is

Filters are logical expressions used to filter arrays. Below are examples of a JSONPath expression with the filters.
// All books in store expensive than 10
String expensiveBook = JsonPath.read(jsonString, "$.store.book[?(@.price > 10)]").toString();
System.out.println("--------------- All books in store costlier than 10 ---------------");
System.out.println(expensiveBook);
// All books in store that are not "expensive"
String notExpensiveBook = JsonPath.read(jsonString, "$..book[?(@.price <= $['expensive'])]").toString();
System.out.println("--------------- All books in store that are not expensive ---------------");
System.out.println(notExpensiveBook);
// All books in store that are equal to price 8.95
String comparePrice = JsonPath.read(jsonString, "$.store.book[?(@.price == 8.95)]").toString();
System.out.println("--------------- All books in store that are not expensive ---------------");
System.out.println(comparePrice);
// All books matching regex (ignore case)
String regxExample = JsonPath.read(jsonString, "$..book[?(@.author =~ /.*REES/i)]").toString();
System.out.println("--------------- All books matching regex (ignore case) ---------------");
System.out.println(regxExample);
// All books with price equal to mentioned list of prices
String priceList = JsonPath.read(jsonString, "$..book[?(@.price in ['12.99', '8.99'])]").toString();
System.out.println("--------------- All books with price equal to mentioned list of prices ---------------");
System.out.println(priceList);
// All books with price NOT equal to mentioned list of prices
String excludePriceList = JsonPath.read(jsonString, "$..book[?(@.price nin ['12.99', '8.99'])]").toString();
System.out.println("---------- All books with price NOT equal to mentioned list of prices ---------");
System.out.println(excludePriceList);
// All books with specified substring (case-sensitive)
String substringExample = JsonPath.read(jsonString, "$..book[?(@.author contains 'Melville')]").toString();
System.out.println("--------------- All books with specified substring (case-sensitive) ---------------");
System.out.println(substringExample);
// All books with an ISBN number
String specificBook = JsonPath.read(jsonString, "$..book[?(@.isbn)]").toString();
System.out.println("--------------- All books with an ISBN number ---------------");
System.out.println(specificBook);
The output of the above program is

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
Last Updated On
In the last tutorial, I explained How to test POST Request using Rest Assured where the request body is in String Format. In this tutorial, I will create a request body using JSON Object in Rest Assured. This request body can be used for POST or PUT operations.
First, set up a basic Rest Assured Maven Project by clicking here and a Gradle project by clicking here.
In the previous post, you must have observed that I had hard-coded the JSON request body in a string format. It is not a good practice if you have a dynamic payload or want to create a payload at run time or parameterized one. It is always recommended to create a payload in a way that is easy to maintain. You should manage, update, and retrieve value from it easily. This can be achieved by JSONObject or JSONArray.
A JSONObject is an unordered collection of key and value pairs, resembling Java’s native Map implementations. JSON stores data as a key-value pair. The key is the left side and the value is the right side, and a semicolon is used to separate both. One key-value pair is separated from another key-value pair using a comma (,).
The internal form is an object having the get and opt methods for accessing the values by name and put methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or JSONObject.NULL object.
To create a request body using JSON Object, we need to add a Maven dependency.
<dependencies>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20240303</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.5.0</version>
<scope>test</scope>
</dependency>
</dependencies>
JSONObject is imported from package:-
import org.json.JSONObject;
JSONObject exposes an API similar to Java’s Map interface. Below is an example of creating a request from a JSON Object. Here, Id is the auto-generated attribute. We are using the put() method and supply the key and value as an argument. I am using a logger just to print the JSON body in the Console.
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.json.JSONObject;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
public class Json_Demo {
@Test
public void passBodyAsJsonObject() {
JSONObject data = new JSONObject();
data.put("employee_name", "MapTest");
data.put("profile_image", "test.png");
data.put("employee_age", "30");
data.put("employee_salary", "11111");
RestAssured
.given()
.contentType(ContentType.JSON)
.body(data.toString())
.log().all()
.when()
.post("https://dummy.restapiexample.com/api/v1/create")
.then()
.assertThat().statusCode(200)
.body("data.employee_name", equalTo("MapTest"))
.body("data.employee_age", equalTo("30"))
.body("data.employee_salary", equalTo("11111"))
.body("data.profile_image", equalTo("test.png"))
.body("message", equalTo("Successfully! Record has been added."))
.log().all();
}
}
The request body will look as shown below:-


The texts produced by the toString() methods strictly conform to the JSON syntax rules.
.body(data.toString())
The above one is a simple JSON Request Body. Let’s take an example of a Complex Request Body or nested Request Body.

We need to create two JSONObject here. One will hold overall key-value pairs, and another JSONObject will hold only employee_details key-value pairs.
Below is an example that shows how to create a complex JSON request body using JSONObject.
@Test
public void passBodyAsJsonObjectDemo() {
//First JSONObject
JSONObject data = new JSONObject();
data.put("profile_image", "test.png");
//Second JSONObject
JSONObject detail = new JSONObject();
detail.put("updated_message", "Details of New Resource");
detail.put("employee_age", "30");
data.put("employee_details", detail);
data.put("employee_name", "MapTest");
data.put("employee_salary", "11111");
RestAssured
.given()
.contentType(ContentType.JSON)
.body(data.toString())
.log().all()
.when()
.post("http://dummy.restapiexample.com/api/v1/create")
.then()
.assertThat().statusCode(200)
.body("data.employee_name", equalTo("MapTest"))
.body("data.employee_details.employee_age", equalTo("30"))
.body("data.employee_details.updated_message", equalTo("Details of New Resource"))
.body("data.employee_salary", equalTo("11111")).body("data.profile_image", equalTo("test.png"))
.body("message", equalTo("Successfully! Record has been added."))
.log().all();
}
}
The request body will look as shown below:-


We are done. Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!