top of page

Rest Assured -Payloads - Part 2

rekhanag

In the last blog, we learnt mostly about using jsonsimple library to send json object payloads on a POST request. Continuing with the same petstore example, we will now see how meta-data or form data can be sent as a payload.


3. In the next example, we tried to read the payload from an external json file


Payload.json is the file in the src/test/resouces package which has the json body stored. This kind of payload helps when a complex payload has to be sent in the post request



@Test (priority=3)
	public void Postrequestusingjsonfilepayload() {
// ------------------add payload jsonfile to Postrequest ------------
System.out.println( "TEST 2 : Post Request : Payload - from .json file" + "==============");
		File jsonData = new File("src/test/resources/payload.json");
		JsonPath expectedjson =new JsonPath((new File(".\\src/test/resources/payload.json")));
			
		Response response = given().accept("application/json")
				.contentType("application/json")// request.header("Content-Type",//"application/json")
					.body(jsonData).log().all()
					.when().post(constants.Base_URL +"pet") // https://petstore.swagger.io/v2/pet
					.then()
					.assertThat()
					.statusCode(200)
					// compare whole json payload to expected response
					.body("",equalTo(expectedjson.getMap("")))
					.log()
					.all()
					.extract()
					.response();
			
			//vaidating json response
			JsonPath jpath = response.jsonPath();// to readable format
		
			// validating Status Code
			int statusCode = response.getStatusCode();
			System.out.println(" Status Code  for Post request is :" + statusCode);
			assertEquals(200, statusCode);
		}

















4. In this example, we are considering an image to be uploaded and sent as request body payload. Its considered to be of type Multi-part/ Form-data


The Swagger request has 3 parts - The pet id, the additional metadata,(Form-data) and a file(Form-data)


Multipart requests combine one or more sets of data into a single body, separated by boundaries. You typically use these requests for file uploads and for transferring data of several types in a single request (for example, a file along with a JSON object).

The screenshot is an image stored in the package src/test/resources



public class TC003_addmetadatatoPostRequest {
@Test
	public void Postrequestwithmetadata() {
		
		File imageUpload= new File("src/test/resources/Screenshot2022-04-3000.23.35.png");
		Response response =	
			  given().baseUri("https://petstore.swagger.io/v2/")
			.contentType("multipart/form-data")
// boundary=<calculated when request is  sent>")
//request.header	("Content-Type", "application/json")
					  		
			.multiPart("file",imageUpload)
			.multiPart("additionalMetadata","doguniverse")
			.log().all()
			  .when()
			.post("pet/203/uploadImage")//https://petstore.swagger.io/v2/pet
			  .then()
			.statusCode(200)
			.log().all()
			 			.body(JsonSchemaValidator.matchesJsonSchemaInClasspath("jsonschemaforpetstore.json")
			.extract()
			.response();
					
			JsonPath jpath = response.jsonPath();// to readable format
			System.out.println(response.body().asString());
								
			// validating Status Code
					  
			 int statusCode = response.getStatusCode();
			 System.out.println( " Status Code  for Post request is :"  + statusCode);
			 assertEquals(200,statusCode);
					
	}

The response out put for the request looks like this



Now, lets consider ObjectMapper class from Jackson Library to send payloads thru POST request body

please refer to my earlier blog to read about Serialization and De-serialization


Object Mapping

The ObjectMapper class is the most important class in the Jackson library. We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.Class ObjectMapper is used to create a JSON Object or ObjectNode.



For Maven projects, the following dependency is needed in the ‘pom.xml file.’

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.11.0</version>
</dependency>

Here, we will be using a method named ‘writeValueAsString()’ in the code and that can be used to serialize any Java value as a String. Here we are passing HashMap of data as objects, and it serializes them as strings. As ObjectMapper is used, it writes JSON string.


Consider the following example;

JSON String -

{
     "name": "Jim",
     "age": 15,
     "grade": 10,
     }

To convert any object of the above Pojo class to a JSON object, we need to perform the below steps:-


1.Create an object of POJO class.

2.Set values of properties of Pojo class

3.Create an object of ObjectMapper class provided by Jackson.

4.Use overloaded writeXXXXXX() method as per need. we can convert POJO object to JSON string.


ObjectMapper is the main essential class in Jackson library which helps for reading and writing JSON

  1. creating a POJO class - used getter and setter methods.

How to Convert a JSON String into Java Object. So, let's take the help of one of the websites to help us convert the JSON to a Java POJO class.

Please follow these steps

  • Firstly, navigate to the website: http://www.jsonschema2pojo.org/

  • Secondly, enter the JSON body in the left text box.

  • Thirdly, enter the package name and class name in the right-side panel.

  • Finally, enter other required selection details as per the image below.



POJO class generated with getter and setter methods and constructor. This is a very useful tool when you have complex Json payloads.

copy to clipboard looks like this



packagecom.pojoexample;

importjavax.annotation.Generated;

@Generated("jsonschema2pojo")
publicclassStudentpojo {

privateStringname;
privateIntegerage;
privateIntegergrade;

/**
* No args constructor for use in serialization
*
*/
publicStudentpojo() {
}

/**
*
* @param grade
* @param name
* @param age
*/
publicStudentpojo(Stringname, Integerage, Integergrade) {
super();
this.name=name;
this.age=age;
this.grade=grade;
}

publicStringgetName() {
returnname;
}

publicvoidsetName(Stringname) {
this.name=name;
}

publicIntegergetAge() {
returnage;
}

publicvoidsetAge(Integerage) {
this.age=age;
}

publicIntegergetGrade() {
returngrade;
}

publicvoidsetGrade(Integergrade) {
this.grade=grade;
}

}

Using Object Mapper , we can now send a json as pojo payload

package ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
 
import pojo.student;
 
public class ConvertPojoToJson {
 
	public static void main(String[] args) throws JsonProcessingException {
	// Create object of Pojo and set values

		student stu = new student();
		student.setname("Jim");
		student.setage(15);
		student.setgrade(10);
		
	// ObjectMapper class to serialize Pojo object to JSON
		
		ObjectMapper objectMapper = new ObjectMapper();
		String json = objectMapper.writerWithDefaultPrettyPrinter()
								.writeValueAsString(student);
		System.out.println("Json Object is :-");
		System.out.println(json);
		
	//deserializing json to string

		ObjectMapper mapper = new ObjectMapper();
      	String jsonString = "";
     	 Map<String, int> map = new HashMap<String, int>();
      	 map.put("name", "Jim");
    		 map.put("age", 15);
    		 map.put("grade",10);
    
      	jsonString = mapper.writeValueAsString(map); 
      // converts Map to JSON
      
		System.out.println(map);
		}
	}

Output :



Json Object is :-
{
  "name" : "Jim",
  "age"  : 15,
  "grade":10
}

{"name":"Jim", "age": 15, "grade":10}


Similar to JSONobjects , Objectmapper can be used to convert a json pay load to pojo, hashmap or list.


Hope this article helped you understand how payloads work.

573 views

Recent Posts

See All
bottom of page