How to test POST request from JSON Object in Rest Assured

HOME

In the last tutorial, I have explained How to test POST Request using Rest Assured where 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, setup a basic Rest Assured Maven Project by clicking here and 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 the dynamic payload or want to create a payload at run time or parameterized one. It is always recommended to create a payload in such a way that you can easily maintain, manage, update, and retrieve values from it. This can be achieved by JSONObject or JSONArray.

JSONObject is an unordered collection of key and value pairs, resembling Java’s native Map implementations. JSON stores data as a key-value pair. Key is left side and 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 comma (,).

The internal form is an object having to 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 the JSONObject.NULL object.

To create a request body using JSON Object, we need to add a maen dependency.

<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20210307</version>
</dependency>   

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 JSON Object. Here, Id is 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. 

@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("http://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())

Above one is a simple JSON Request Body. Lets take an example of 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 the example which 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!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s