</>

Technology

Rest Assured

Difficulty

Beginner

Interview Question

How to automate GET method and fetch/validate response body using Rest Assured?

Answer

Fetch and Validate Response Body in Rest Assured

Fetch Entire Response Body

Java
@Test(description = "Automate GET method and fetch response body")
public static void verifyResponseBody() {

    Response resp = given()
                        .when()
                        .get("https://reqres.in/api/users/2");

    assertEquals(resp.getBody().asString(), 200); // Note: getBody() returns body as String
    System.out.println(resp.getBody().asString());
}

Validate Specific Field Value from Response Body

Java
@Test(description = "Verify value from response body - validate total pages = 12")
public static void verifyValueFromResponseBody() {

    Response resp = given()
                        .when()
                        .get("https://reqres.in/api/users");

    System.out.println(resp.path("total").toString());

    assertEquals(resp.getStatusCode(), 200);
    assertEquals(resp.path("total").toString(), "12");
}

Using JsonPath to Extract Values

Java
@Test
public void extractNestedValue() {
    Response resp = given()
                        .when()
                        .get("https://reqres.in/api/users/2");

    // Extract nested field: data.first_name
    String firstName = resp.jsonPath().getString("data.first_name");
    System.out.println("First Name: " + firstName);
    assertEquals(firstName, "Janet");
}

BDD Style with Body Assertions

Java
given()
    .when()
    .get("https://reqres.in/api/users")
    .then()
    .statusCode(200)
    .body("total", equalTo(12))
    .body("page", equalTo(1))
    .body("data[0].email", containsString("@reqres.in"));

Key Methods for Response Body

MethodUse Case
resp.getBody().asString()Entire body as String
resp.path("key")Extract top-level JSON field
resp.jsonPath().getString("nested.key")Extract nested field
.body("key", equalTo(value))BDD assertion on field

Follow AutomateQA

Related Topics