Different Ways of Sending JSON Payload in Rest Assured

Introduction

In this article, we will learn about what are the different ways we can send the json payload in the post http request.

Prerequisite

There are many ways we can send the json payload in the post http request; I will teach you three ways that I am comfortable with.

Step 1. Directly hardcode the json data in the string variable and then refer to it in a given section.

Code explained with comments.

@Test
public void createsource() {
    //storing the base uri
    RestAssured.baseURI = "https://reqres.in/";
    //storing the json payload in the string
    String requestBody = "{\n" +
        "    \"email\": \"[email protected]\",\n" +
        "    \"password\": \"cityslicka\"\n" +
        "}";
    // See below we have called the post method in when section which accepts the endpoint as parameter and in the given section we need to provide the json payload in the body method
    Response res = given().contentType(ContentType.JSON).
    body(requestBody).
    when().
    post("api/login").
    then().log().all()
        .extract().
    response();
    //applying assertion on response code
    Assert.assertEquals(200, res.statusCode());
}

Step 2. Create a class file and create a static string variable and store the json data.

Now in your test file, call the static variable using classname.staticvariable name in the body method.

Class file, which contains the test data.

public class testdata {
	
	public static String requestBody = "{\n"
			+ "    \"email\": \"[email protected]\",\n"
			+ "    \"password\": \"cityslicka\"\n"
			+ "}";

}

Code with comments explained.

public class postapi {
		
	@Test
	public void createsource() {
		RestAssured.baseURI="https://reqres.in/";
		
		Response res=given().contentType(ContentType.JSON).
		//we are calling the static variable requestbody which contains the json value from the class testdata
		body(testdata.requestBody).
		when().
		post("api/login").
		then().log().all()
		.extract().
		response();
		
		 Assert.assertEquals(200, res.statusCode());		
		
	}
}

Step 3. Create a POJO class using the serialization concept and convert the POJO class object to json object.

  • Serialization: Convert the class's objects of POJO to JSON or Object representation.
  • Deserialization: Convert a JSON object to an object of the class of POJO.

Dependencies need to achieve Serialization and Deserialization. Kindly add these dependencies in pom.xml and save it. Update your maven project.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.15.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.15.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.9.1</version>
</dependency>

POJO Class

Plain Old Java Object (POJO) refers to a class that encapsulates data and provides getter and setter methods for accessing and modifying that data. POJOs are simple Java classes that do not depend on any specific frameworks or libraries. They are commonly used for modeling data in object-oriented programming.

Example of POJO class

public class Person {
    private String name;
    private int age;

    // Default constructor
    public Person() {
    }

    // Parameterized constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getter for name
    public String getName() {
        return name;
    }

    // Setter for name
    public void setName(String name) {
        this.name = name;
    }

    // Getter for age
    public int getAge() {
        return age;
    }

    // Setter for age
    public void setAge(int age) {
        this.age = age;
    }
}

Create a POJO class

Declare variables in the pojo class; the no of variables that needs to be created depends upon the json key value which you have as test data.

For example, below is my json.

{
	"email": "[email protected]",
	"password": "cityslicka"
}

So I will be creating two variables, email, and password, in the POJO class.

In order to generate getters and setters in Eclipse, right-click in the POJO class and select the source option--> select generate getters and setters option.

We will get a window.

Generate Getter and Setter

Check the getters and setters check boxes of each variable and click generate button.

The getters and setters will automatically be generated.

POJO class

package com.apidemoautomation;

public class Testingdata {
	
	private String email;
	private String password;
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}
  • Now create a test file
  • Inside the test
  • Create an object of the POJO class
  • Call the setter method using the object of the POJO class and set the email and password value.
  • Create an object of objectmapper class
  • ObjectMapper class provides functionality for reading and writing JSON, either to or from the POJO class.
  • The method writeValueAsString ObjectMapper class generates a JSON from a Java object and returns the generated JSON as a string;
  • Now use the jsonstring reference inside the body method in the given section.

Code explained with comments

@Test
public void createsource() throws JsonProcessingException {
    //storing base uri
    RestAssured.baseURI = "https://reqres.in/";
    //creating object of the pojo class
    //set the value for email and password
    Testingdata td = new Testingdata();
    td.setEmail("[email protected]");
    td.setPassword("cityslicka");
    //create object of objectmapper class
    ObjectMapper objectMapper = new ObjectMapper();
    //The methods writeValueAsString ObjectMapper class generate a JSON from a Java object and return the generated JSON as a string;
    String jsonbody = objectMapper.writeValueAsString(td);
    //printing out the json
    System.out.println("jsonstring " + jsonbody);

    Response res = given().contentType(ContentType.JSON).
    //Now use the jsonbody reference inside the body method in the given section.
    body(jsonbody).
    when().
    post("api/login").
    then().log().all()
        .extract().
    response();

    Assert.assertEquals(200, res.statusCode());
}

Deserialization

We can convert a JSON String to a Java object using the ObjectMapper class.

We can use the readValue() method  to parse or deserialize JSON content into a Java object

Code example

//deserialization
Testingdata td1=objectMapper.readValue(jsonbody, Testingdata.class);
System.out.println("prining email value "+td1.getEmail());
System.out.println("prining password  key value "+td1.getPassword());

Summary

I hope this article will be helpful in understanding different ways of sending the json payload in the post http request.

Thanks, Happy learning.