Last Updated On
In this tutorial, I will explain to pass a JSON or XML file as a payload to the request. This is needed when the payload is static or there is minimal change in the request payload. This can be done by using the body() method, which accepts “File” as an argument. This is elaborated in Javadoc.
RequestSpecification body(File body)
This specifies file content that’ll be sent with the request. This only works for the POST, PATCH and PUT HTTP methods. Trying to do this for the other HTTP methods will cause an exception to be thrown.
Add Rest Assured dependency to the project. Use the latest version from here.
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.5.1</version>
<scope>test</scope>
</dependency>
Pass JSON file as payload
Step 1 – Create a .json file and write the payload in that. Keep the file in the “src/test/resources” folder.

Step 2 – Create a File in Java using the “File” and pass it to body() method.
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import java.io.File;
import org.junit.Test;
import io.restassured.http.ContentType;
public class passJsonAsPayload {
@Test
public void createUser() {
// Creating a File instance
File jsonData = new File("src/test/resources/Payloads/jsondemo.json");
// GIVEN
given()
.baseUri("https://reqres.in")
.contentType(ContentType.JSON)
.body(jsonData)
// WHEN
.when()
.post("/api/users")
// THEN
.then()
.assertThat()
.statusCode(201)
.body("name", equalTo("Json_Test"))
.body("job", equalTo("Leader"))
.log().all();
}
}
The output of the above program is

Similarly, we can pass an XML as a payload to request. The file passed within the body() method should be of type .xml.
Pass XML file as payload
Sample XML file is present in src/test/resources.

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<NumberToWords xmlns="http://www.dataaccess.com/webservicesserver/">
<ubiNum>500</ubiNum>
</NumberToWords>
</soap:Body>
</soap:Envelope>
The complete code is shown below:
@Test
public void getNumber() {
// Creating a File instance
File xmlData = new File("src/test/resources/Payloads/xmlDemo.xml");
// GIVEN
RestAssured.given()
.baseUri("https://www.dataaccess.com")
.header("Content-Type", "text/xml")
.body(xmlData)
// WHEN
.when()
.post("/webservicesserver/NumberConversion.wso")
// THEN
.then()
.assertThat()
.statusCode(200)
.body("Envelope.Body.NumberToWordsResponse.NumberToWordsResult", equalToCompressingWhiteSpace("five hundred"))
.log().all();
}
The output of the above program is

Congrats. You have learned how to pass a JSON as a payload to the request. Happy Learning !!