How to handle static JSON in Rest Assured?

We can handle static JSON in Rest Assured. This can be done by storing the entire JSON request in an external file. First, the contents of the file should be converted to String.

Then we should read the file content and convert it to Byte data type. Once the entire data is converted to Byte, we should finally convert it to string. We shall utilize an external JSON file as a payload for executing a POST request.

Let us create a JSON file, say payLoad.json, and add a request body in the below JSON format. This is created within the project.

   "title": "API Automation Testing",
   "body": "Rest Assured",
   "userId": "100"


Code Implementation

import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import io.restassured.RestAssured;
public class NewTest {
   void readJSONfile() throws IOException {

      //read data from local JSON file then store in byte array
      byte[] b = Files.readAllBytes(Paths.get("payLoad.json"));

      //convert byte array to string
      String bdy = new String(b);

      //base URL
      RestAssured.baseURI = "";

      //input details with header and body
      given().header("Content-type", "application/json").body(bdy)

      //adding post method

      //verify status code as 201


Updated on: 17-Nov-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started