How To Use Java Object As Payload For API Request

Earlier we have learned to Create JSON payload using Jackson API. Now we will learn to use that JSON payload in a request using Rest Assured.

body(Object object)

When we create a JSON Object using Jackson API then it is a type of ObjectNode class which is a Node that maps to JSON Object structures in JSON content.

Interface RequestSpecification has multiple overloaded body() methods and one of the overloaded methods is RequestSpecification body(Object object). This method will be automatically serialized passed object to JSON or XML and sent with the request.

Rule of Serialization

Whether it will be serialized to JSON or XML that depends upon what we pass as Content-Type. If we pass Content-Type as application/json then Rest Assured will serialize the Object to JSON. To serialize to JSON , Rest Assured will look for which JSON parser is available in class path. First it looks for Jackson. If Jackson is not found it looks for GSON. If both are not found then an exception IllegalArgumentException stating “Cannot serialize because no JSON or XML serializer found in classpath.” will be thrown.

If we pass Content-Type as “application/xml” then Rest Assured will serialize Object in to XML and for that it looks for JAXB library in class path of project. If it is not found then an exception IllegalArgumentException stating “Cannot serialize because no JSON or XML serializer found in classpath.” will be thrown.

If we do not pass any Content-Type then Rest Assured will first try to parse in JSON using Jackson library. If Jackson is not found, it will look for GSON. If both are not found, it will parse in to XML using JAXB. If none found, exception will be thrown.

Note :- This works for the POST and PUT methods only.

So when we create a JSON payload using Jackson API, we can pass it directly to body() method. It will be good to pass Content-Type in Request Specification as well because Rest Assured will parse payload in to JSON or XML but API may not able to understand the payload type.

Rest Assured Example

package DifferentWaysOfPassingPayloadToRequest;
 
import org.testng.annotations.Test;
 
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
 
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
 
public class UseCreatedJsonObjectUsingJacksonAPIPayload {
	
	@Test
	public void CreatingNestedJsonObjectTest() throws JsonProcessingException
	{
		// Create an object to ObjectMapper
		ObjectMapper objectMapper = new ObjectMapper();
		
		// Creating Node that maps to JSON Object structures in JSON content
		ObjectNode bookingDetails = objectMapper.createObjectNode();
		
		// It is similar to map put method. put method is overloaded to accept different types of data
		// String as field value
		bookingDetails.put("firstname", "Jim");
		bookingDetails.put("lastname", "Brown");
		// integer as field value
		bookingDetails.put("totalprice", 111);
		// boolean as field value
		bookingDetails.put("depositpaid", true);
		bookingDetails.put("additionalneeds", "Breakfast");
		// Duplicate field name. Will override value
		bookingDetails.put("additionalneeds", "Lunch");
		
		// Since requirement is to create a nested JSON Object
		ObjectNode bookingDateDetails = objectMapper.createObjectNode();
		bookingDateDetails.put("checkin", "2021-07-01");
		bookingDateDetails.put("checkout", "2021-07-01");
		
		// Since 2.4 , put(String fieldName, JsonNode value) is deprecated. So use either set(String fieldName, JsonNode value) or replace(String fieldName, JsonNode value)
		bookingDetails.set("bookingdates", bookingDateDetails);
		
		
		//GIVEN
		RestAssured
		   .given()
			  .baseUri("https://restful-booker.herokuapp.com/booking")
			  .contentType(ContentType.JSON)
			  // Pass JSON pay load directly
			  .body(bookingDetails)
			  .log()
			  .all()
		// WHEN
		   .when()
			   .post()
		// THEN
		   .then()
			   .assertThat()
			   .statusCode(200)
			   .log()
			   .all();
	}
 
}

Output

Request method:	POST
Request URI:	https://restful-booker.herokuapp.com/booking
Proxy:			<none>
Request params:	<none>
Query params:	<none>
Form params:	<none>
Path params:	<none>
Headers:		Accept=*/*
				Content-Type=application/json; charset=UTF-8
Cookies:		<none>
Multiparts:		<none>
Body:
{
    "firstname": "Jim",
    "lastname": "Brown",
    "totalprice": 111,
    "depositpaid": true,
    "additionalneeds": "Lunch",
    "bookingdates": {
        "checkin": "2021-07-01",
        "checkout": "2021-07-01"
    }
}
HTTP/1.1 200 OK
Server: Cowboy
Connection: keep-alive
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 191
Etag: W/"bf-nCM7EnDCmzlaWrHH0RxWhtrWq9Y"
Date: Mon, 11 May 2020 10:01:42 GMT
Via: 1.1 vegur
 
{
    "bookingid": 19,
    "booking": {
        "firstname": "Jim",
        "lastname": "Brown",
        "totalprice": 111,
        "depositpaid": true,
        "bookingdates": {
            "checkin": "2021-07-01",
            "checkout": "2021-07-01"
        },
        "additionalneeds": "Lunch"
    }
}
PASSED: CreatingNestedJsonObjectTest