Q7 of 40 · REST Assured
What's the difference between body() and extract() in a REST Assured chain?
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"));
}