How to get a value from a nested list in Rest Assured?

Rest AssuredDynamic ProgrammingProgramming

We can get a value from a nested list in Rest Assured. This is done with the help of the extract method. To grab the item, we have to use the path method(after the extract method) and pass the item in the response we want to obtain.

We shall first send a GET request via Postman on a mock API URL and go through its Response having a nested list.

Example

Code Implementation

import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import java.util.ArrayList;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
public class NewTest {
   @Test
   public void getRequest() {

      //base URL
      RestAssured.baseURI = "https://run.mocky.io/v3";
      RestAssured.basePath =
      "/23ab8486-7d8d-41e4-be27-d603c767d745";

      //response from GET request
      given()
      .when().get().prettyPrint();

      //extract values from Response
      String name = given().contentType(ContentType.JSON).get()
      .then().extract().path("name");
      System.out.println(name);
      String age = given().contentType(ContentType.JSON).get()
      .then().extract().path("age");
      System.out.println(age);

      //extract values from a nested list in Response
      ArrayList<String> s = given().contentType(ContentType.JSON).get()
      .then().extract().path("subjects");
      for(String subject: s) {
         System.out.println(subject);
      }
   }
}

Output

raja
Updated on 22-Nov-2021 10:02:42

Advertisements