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 …
Continue reading How To Use Java Object As Payload For API RequestHow 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
About Jackson API Jackson API is a high performance JSON processor for Java. We can perform serialization, deserialization , reading a JSON file, writing a JSON file and a lot more things using Jackson API. To use Jackson API, we need to add it in java project build path. You can add using Maven or …
Continue reading How To Create A JSON Object Using Jackson API – ObjectMapper – CreateObjectNode()An API may accept a JSON Array payload as well. For example:- Booking for multiple passengers at once. In this case, we may need to pass multiple JSON objects within a JSON array. An example is below:- I just twisted Restful Booking API for multiple bookings at once. We need to add as many JSON …
Continue reading Creating JSON Array Request Body Using ListWe can create a JSON Object using a Map in Java. You must note here that I am using the word “JSON Object”. A JSON Object is a key-value pair and can be easily created using a Java Map. A Map in Java also represents a collection of key-value pairs. Start with a very simple …
Continue reading Creating JSON Object Request Body Using Java MapJSON stands for “JavaScript Object Notation” which is a lightweight , language independent and self describing format in text for data storing and interchange. JSON is easy to read, write and create for humans which makes it famous over XML. JSON was derived from JavaScript but now it is supported by many languages. A file …
Continue reading Introduction To JSONWhen a request is sent to a server, it responds with a response. The amount of time taken between sending a request to server and retrieving a response back form a server is called Response Time. An API must be faster. As a part of API testing, we must check the response time as well. …
Continue reading Get & Assert Response Time Of RequestYou may required to save API response in to an external file like text or JSON etc file for future reference or as a proof. In this post, we will concentrate on saving response in a text file. Rest Assured provides below methods to get response as:- As byte array :- asByteArray() As input stream …
Continue reading Writing Response In A Text FileSuppose you have a request payload (JSON or XML) in a file and you required to directly send that file as a payload to request in stead of reading it first and then passing. Sending file as a payload directly is a good idea when you have static payloads or minimal modification. “body()” method of …
Continue reading How To Send A JSON/XML File As Payload To RequestWriting response into a JSON file Rest Assured provides below methods to get a response as:- As byte array :- asByteArray() As input stream :- asInputStream() As string :- asString() All the above methods output can be used to write into a JSON file. Example program Output Refresh the project folder if you are using …
Continue reading Write API Response In A JSON FileStatic members of a class When we use a “static” modifier with the declaration of a member of a class is called a static member of that class. It is also called a class member. We can use static with a variable, method, inner class, and blocks. Static members are associated with the class, not with …
Continue reading Reason for Static Import In RestAssured