Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
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
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

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.

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

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"
}


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");


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();

    }

}


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"
    }
]


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);


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();
    }
}

 

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!

Previous article
REST Assured – Introduction to JSON and how to send files as Payload
Next article
REST Assured – How To Create a JSON Object and array Using Jackson API – ObjectMapper(createObjectNode())
Live masterclass