Table of contents
1.
Introduction📃
2.
REST Assured💢
3.
Creating JSON Object Request Body Using Java Map💻
4.
Creating JSON Array Request Body Using Java List🧑‍💻
5.
Frequently Asked Questions
5.1.
What is API?
5.2.
What is REST API?
5.3.
What is REST Assured?
5.4.
What is JSON?
5.5.
What is List in Java?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

REST Assured – Creating JSON Object and Array Request Body

Author Rajat Agrawal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction📃

Since you are reading this blog, I think you are familiar with REST APIs. But if you are unfamiliar with REST API, you can learn from this blog on REST API

API

In this blog, we will learn how to create JSON Object and Array request body in REST Assured. But Before learning how to create JSON Object and Array request body in REST Assured, let’s get familiar with REST Assured. 

REST Assured💢

REST Assured is an Open Source Java library for testing and validating REST APIs. It is a Java DSL for HTTP Builder that makes it easier to test REST-based services. 

REST Assured

Any HTTP method is supported by REST Assured, but it specifically supports POSTGETPUTDELETEOPTIONSPATCH, and HEAD. It also simplifies providing and validating things like arguments, headers, cookies, and body.

The response to these requests can be used to validate and verify them.

Let’s see how to create JSON objects in REST Assured.

Creating JSON Object Request Body Using Java Map💻

It is not a good practice to hardcode the JSON request body if you want to create a payload at run time or if you have the dynamic payload. It is best practice to create a payload that you can easily maintain, manage, update, and retrieve values from it.

We can easily create JSON object using Map in Java because both support the key-value pairs feature.

Let’s understand this with the help of an example.

Let’s take a simple JSON object. 

{
    "username" : "CodingNinjas",
    "password" : "ninjas@123",
    "firstname" : "Coding",
    "lastname" : "Ninjas"
}
You can also try this code with Online Java Compiler
Run Code


The Java Map for the above JSON object is created below, Since all the key-value pairs are string, we can create a generic Map.

Map<String,String> authorizationPayload = new HashMap<String,String>();
authorizationPayload.put("username", "CodingNinjas");
authorizationPayload.put("password", "ninjas@123");
authorizationPayload.put("firstname", "Coding");
authorizationPayload.put("lastname", "Ninjas");
You can also try this code with Online Java Compiler
Run Code


Complete Example

package CodingNinjas;

import java.util.HashMap;
import java.util.Map;

import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;

public class CreatingJSONRequestBodyUsingMap {

    @Test
    public void bodyAsMap() {
        Map<String, String> authorizationPayload = new HashMap<String, String>();
        authorizationPayload.put("username", "CodingNinjas");
        authorizationPayload.put("password", "ninjas@123");
        authorizationPayload.put("firstname", "Coding");
        authorizationPayload.put("lastname", "Ninjas");

        // GIVEN
        RestAssured
                .given()
                .baseUri("https://restful-booker.herokuapp.com/auth")
                .contentType(ContentType.JSON)
                .body(authPayload)
                .log()
                .all()

                // WHEN
                .when()
                .post()

                // THEN
                .then()
                .assertThat()
                .statusCode(200)
                .log()
                .all();

    }

}
You can also try this code with Online Java Compiler
Run Code


Output

Using a logger to show the JSON body, you can see the request body in the below output.

JSON body output

Creating JSON Array Request Body Using Java List🧑‍💻

An API may accept a JSON Array payload as well. We can easily create a JSON array using List in Java. 

Let’s understand this with the help of an example.

Let’s take a simple JSON array.

[
    {
        "username" : "CodingNinjas",
        "password" : "ninjas@123"
    },
    {
        "firstname" : "Coding",
        "lastname" : "Ninjas",
        "city":"Noida"
    }
]
You can also try this code with Online Java Compiler
Run Code


The Java List for the above JSON array is created below.

// JSON Object 
Map<String,String> authorizationPayload = new HashMap<String,String>();
authorizationPayload.put("username", "CodingNinjas");
authorizationPayload.put("password", "ninjas@123");

Map<String,String> detailsPayload = new HashMap<String,String>();
detailsPayload.put("firstname", "Coding");
detailsPayload.put("lastname", "Ninjas");
detailsPayload.put("city", "Noida");

// Creating JSON array to add both JSON objects
List<Map<String,Object>> arrayJSONPayload = new ArrayList<>();

arrayJSONPayload.add(authorizationPayload);
arrayJSONPayload.add(detailsPayload);
You can also try this code with Online Java Compiler
Run Code


Complete Example

package CodingNinjas;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

import org.testng.annotations.Test;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;

public class CreatingJSONArray {

    @Test
    public void CreatingJSONObjectTest() {
        // JSON Object
        Map<String, String> authorizationPayload = new HashMap<String, String>();
        authorizationPayload.put("username", "CodingNinjas");
        authorizationPayload.put("password", "ninjas@123");

        Map<String, String> detailsPayload = new HashMap<String, String>();
        detailsPayload.put("firstname", "Coding");
        detailsPayload.put("lastname", "Ninjas");
        detailsPayload.put("city", "Noida");

        // Creating JSON array to add both JSON objects
        List<Map<String, Object>> arrayJSONPayload = new ArrayList<>();

        arrayJSONPayload.add(authorizationPayload);
        arrayJSONPayload.add(detailsPayload);

        // GIVEN
        RestAssured
                .given()
                .baseUri("https://restful-booker.herokuapp.com/auth")
                .contentType(ContentType.JSON)
                .body(arrayJSONPayload)
                .log()
                .all()

                // WHEN
                .when()
                .post()

                // THEN
                .then()
                .assertThat()

                // Putting status code as 500 
                .statusCode(500)
                .log()
                .all();
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Output

You can see the JSON Array body in the output.

JSON Array Output

Must Read Array of Objects in Java

Frequently Asked Questions

What is API?

API stands for Application Programming Interface. It is a set of definitions and protocols for creating and integrating software applications. 

What is REST API?

REST (Representational State Transfer) is an architectural paradigm for establishing web services that define a set of requirements. REST API is a straightforward and flexible approach to accessing online services without going through any processing.

What is REST Assured?

REST Assured is an Open Source Java library for testing and validating REST APIs. It is a Java DSL for HTTP Builder that makes it easier to test REST-based services.

What is JSON?

JSON is a free and open-source file format and data exchange format that uses text that can be read by humans to store and send data objects made up of arrays and attribute-value pairs.

What is List in Java?

List in Java is the data structure to maintain the ordered collection. It contains index-based methods to insert, delete, update, and search the elements.

Conclusion

In this article, we have extensively discussed how to create JSON Object and Array request body in REST Assured. I hope you enjoyed reading this article on REST Assured – Creating JSON Object and Array Request Body.

If you want to learn more, check out our articles on Ignore Default and Null values in Payload in Rest AssuredImplementing DELETE Method to Delete a User ResourceTechnological Services in Ready APIWhat Is Web2Py?Why To Use Web2py?Postbacks and Internationalization in web2pyThird Party Modules In Web2pyTasks In Web2py, and  XML in Web2py.

Recommended problems -

 

Also, check out these exciting courses from coding ninjas to expand your knowledge, Coding CourseCode StudioInterview ExperienceGuided PathInterview ProblemsTest SeriesLibrary, and Resources

Happy Coding!

Live masterclass