Q7 of 40 · REST Assured

What's the difference between body() and extract() in a REST Assured chain?

REST AssuredJuniorrest-assuredextractassertionsapi-testing

Short answer

Short answer: .body(path, matcher) asserts a value and stays in the chain — it returns ValidatableResponse. .extract() ends the chain and returns a typed value for use in subsequent Java code, such as capturing a created resource's ID for a follow-up GET. Assert first, extract last.

Detail

.body(path, matcher) is for assertions only. It does not return a value usable in Java — it returns ValidatableResponse for further chaining.

.extract() breaks out of the assertion chain and returns ExtractableResponse, from which you pull values:

int newId = given()...when().post("/users").then()
    .statusCode(201)
    .extract().path("id");           // pulls a scalar

User user = ...then().extract().as(User.class);   // maps to POJO

String location = ...then().extract().header("Location");

Once you call .extract(), you cannot add more matchers — it ends the chain. The pattern is: assert everything you need to verify, then extract at the end.

Common pattern: POST → extract ID → GET with extracted ID → assert the GET response.

// EXAMPLE

@Test
void createThenGet_roundTrip() {
    // POST — assert 201, extract the new ID for the follow-up
    int userId = given()
        .baseUri("https://api.example.com")
        .contentType(ContentType.JSON)
        .body("{ \"name\": \"Alice\", \"email\": \"alice@example.com\" }")
    .when()
        .post("/users")
    .then()
        .statusCode(201)
        .body("name", equalTo("Alice"))  // assert first
        .extract().path("id");           // then extract

    // GET — use the extracted ID
    given()
        .baseUri("https://api.example.com")
    .when()
        .get("/users/" + userId)
    .then()
        .statusCode(200)
        .body("id",   equalTo(userId))
        .body("name", equalTo("Alice"));
}

// WHAT INTERVIEWERS LOOK FOR

Clear distinction between assertion (body) and extraction (extract), and the practical pattern of extracting IDs or Location headers from a create response to drive follow-up requests. Knowing that extract ends the chain.

// COMMON PITFALL

Skipping .body() assertions and only using .extract() + manual assertEquals — this loses REST Assured's readable failure messages and breaks the intended usage pattern.