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"
}

Example

Code Implementation

import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import io.restassured.RestAssured;
public class NewTest {
   @Test
   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 = "https://jsonplaceholder.typicode.com";

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

      //adding post method
      .when().post("/posts").then().log().all()

      //verify status code as 201
      .assertThat().statusCode(201);
   }
}

Output

Updated on: 17-Nov-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements