</>

Technology

Rest Assured

Difficulty

Intermediate

Interview Question

How to extract values from response using extract() and JsonPath in Rest Assured?

Answer

Extracting Values in Rest Assured

Rest Assured provides multiple ways to extract data from API responses for use in subsequent requests (API chaining).

Method 1: extract().path() — Extract Single Field

Java
// Extract a single field directly
String userId = given()
                    .contentType(ContentType.JSON)
                    .body("{ \"name\": \"John\", \"job\": \"QA\" }")
                    .when()
                    .post("/api/users")
                    .then()
                    .statusCode(201)
                    .extract()
                    .path("id");

System.out.println("Created user ID: " + userId);

Method 2: extract().jsonPath() — Extract Multiple Fields

Java
Response response = given()
                        .when()
                        .get("/api/users/2")
                        .then()
                        .statusCode(200)
                        .extract()
                        .response();

JsonPath jsonPath = response.jsonPath();

String firstName = jsonPath.getString("data.first_name");
String lastName  = jsonPath.getString("data.last_name");
String email     = jsonPath.getString("data.email");
int    id        = jsonPath.getInt("data.id");

System.out.println(firstName + " " + lastName + " - " + email);

Method 3: extract().as() — Deserialize to POJO

Java
UserResponse user = given()
                        .when()
                        .get("/api/users/2")
                        .then()
                        .statusCode(200)
                        .extract()
                        .as(UserResponse.class); // deserialization

assertEquals(user.getData().getFirstName(), "Janet");

Method 4: extract() from Array

Java
// Extract list of all email addresses
List<String> emails = given()
                          .when()
                          .get("/api/users")
                          .then()
                          .extract()
                          .jsonPath()
                          .getList("data.email");

emails.forEach(System.out::println);

Method 5: Extract Response as String

Java
String responseBody = given()
                          .when()
                          .get("/api/users/1")
                          .then()
                          .extract()
                          .asString();

System.out.println(responseBody);

Common JsonPath Expressions

ExpressionGets
"name"Top-level "name" field
"data.email"Nested "email" inside "data"
"data[0].id"First item in "data" array
"data.findAll { it.id > 3 }.email"Filter array and get emails
"data.size()"Array length

Follow AutomateQA

Related Topics