Post

Extract Values From a Response in REST Assured

Get values out of a response after checking it, covering extract().path(..) for a value and a list, a kept ExtractableResponse with headers and the status, extract().response(), and a value used in the next request.

Extract Values From a Response in REST Assured

Your onboarding test creates a customer, and then needs the new customer’s id to read it back. A colleague’s test takes the name from a response without checking the status, and fails three lines later with a NullPointerException, nowhere near the real cause: the customer didn’t exist. In this guide, you’ll take values out of a response with extract(), use them in Java and in the next request, and always check the response first.

Level: Intermediate · Time: 20 minutes · Part of: Module 4: Extracting Values and Mapping Objects, section 1

What You’ll Build

You’ll build a test class called ExtractingValuesTest with five tests. They extract a single value, a list, several parts of one response and the whole response, and use a value from one response in the next request.

One of the tests creates a customer and reads several parts of the response:

1
2
3
4
5
6
7
8
9
10
11
POST /api/v1/customers HTTP/1.1
Host: localhost:<port>
Content-Type: application/json

{"name":"Pieter Post","email":"pieter@example.nl","segment":"RETAIL"}

HTTP/1.1 201 Created
Content-type: application/json; charset=utf-8
Location: /api/v1/customers/cust-6

{"id":"cust-6","name":"Pieter Post","email":"pieter@example.nl","segment":"RETAIL", ...}

When you’re done, Maven reports five passing tests:

1
2
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

In this guide, you will:

  • Extract a value and a list.
  • Read several parts of one response.
  • Use a value in the next request.

What You Need

How to Complete This Guide

You can work through this guide in one of two ways:

  • Build it step by step: this is the first section of Module 4, so you start from scratch. Create ExtractingValuesTest in the module-04 test sources and follow every heading below.
  • Skip ahead: open the finished class (ExtractingValuesTest.java) and read along. You can run it at any time with the command in Run the Tests.

Get the code: clone the examples repository and change into it:

1
2
git clone https://github.com/javanibble/rest-assured-examples.git
cd rest-assured-examples

If you’ve already cloned it for an earlier module, run git pull instead.

Out of scope: this guide doesn’t cover typed getters on JsonPath, mapping a body to a record, or chaining a whole flow of requests; they’re taught in section 2, section 3 and section 5.

Understand extract()

The problem. Checks answer “is this response right?” Many tests also need a value from the response for what comes next: the id of a customer the test created, the second item on a page, the Location header to follow. Taking a value without checking the response first turns a wrong response into a null, and the test fails later with an error that hides the cause.

The concept. extract() ends the validation chain and returns an ExtractableResponse. From it you can read:

WhatHow
A value or a listpath("name"), with the same GPath as body(..)
A header or the statusheader("Location"), statusCode(), contentType()
The whole responseresponse(), a Response you can read or check again
The body as an objectas(..) and jsonPath(), in sections 2 and 3

Because extract() comes after then(), every check before it runs first. That order is the point.

When to use it. Extract the values you need later: in Java, in the next request, or in a check that compares two values. For a value you only want to check, use body(..) in the chain: it’s shorter, and its failure message is better than assertEquals(..)’s.

Validate first, extract second.

Meet the API Under Test

Module 4 tests a Customers and Consents API, modelled on open banking account access consents. It runs on the JDK’s built-in HTTP server, like the APIs of the earlier modules, starts on a free port and serves its endpoints under /api/v1. This section uses its customers:

MethodPathPurpose
GET/customers/{id}Fetch one customer, or 404
GET/customersFetch a page of customers, with page and size
POST/customersCreate a customer, with a Location header

Five customers exist at start-up, cust-1 to cust-5. GET /api/v1/customers/cust-1 returns:

1
2
3
4
5
6
7
{
    "id": "cust-1",
    "name": "Anna de Vries",
    "email": "anna@example.nl",
    "segment": "RETAIL",
    "createdAt": "2026-11-21T19:19:31.832047Z"
}

GET /api/v1/customers?size=2 returns a page, shortened:

1
2
3
4
5
6
7
8
9
10
{
    "items": [
        { "id": "cust-1", "name": "Anna de Vries", "segment": "RETAIL", ... },
        { "id": "cust-2", "name": "Jan Jansen", "segment": "RETAIL", ... }
    ],
    "page": 0,
    "size": 2,
    "totalItems": 5,
    "totalPages": 3
}

Without size, a page holds up to 10 customers, which includes the two BUSINESS ones. An unknown customer gets a 404 problem with the detail Customer cust-99 does not exist.

Your tests extract these values:

  • name and segment of a single customer.
  • items.segment and items[1].id from a page.
  • id and the Location header of a new customer, such as cust-6 and /api/v1/customers/cust-6.

Extract a Value and a List

Set Up the Test Class

Goal: create the test class, start the Consents API and add a shared request helper.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.javanibble.module_04.section_01;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.javanibble.consents.ConsentsApi;
import com.javanibble.module_04.support.Models.NewCustomer;

import io.restassured.http.ContentType;
import io.restassured.response.ExtractableResponse;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;

import java.util.List;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

class ExtractingValuesTest {

    private static ConsentsApi api;

    @BeforeAll
    static void startApi() {
        api = ConsentsApi.start();
    }

    @AfterAll
    static void stopApi() {
        api.close();
    }

    private static RequestSpecification consentsApi() {
        return given().baseUri(api.baseUri()).port(api.port()).basePath(ConsentsApi.BASE_PATH);
    }
}

What’s happening:

  • ConsentsApi is Module 4’s test server. It starts and stops like the APIs of the earlier modules.
  • consentsApi() returns a request with the base URI, port and base path /api/v1 set.
  • NewCustomer is a record from the module’s Models class, the tests’ own view of the API’s JSON.

Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.

Extract One Value by Path

Goal: check the response, then take a customer’s name into a variable.

1
2
3
4
5
6
7
8
9
10
11
@Test
void extractOneValueByPath() {
    String name = consentsApi()
    .when()
        .get("/customers/{id}", "cust-1")
    .then()
        .statusCode(200)
        .extract().path("name");

    assertEquals("Anna de Vries", name);
}

What’s happening:

  • statusCode(200) runs first, so a wrong response fails here, with a clear message.
  • extract().path("name") reads the value at name, with the same GPath as body(..).
  • path(..) is generic, so Java infers the type from the variable you assign it to. There’s no conversion: a JSON string is a String.

Checkpoint: run ExtractingValuesTest from your IDE. One test runs and passes.

The variable’s type must match the type REST Assured read. Long total = extract().path("totalItems") compiles, but a whole number is an Integer, so it throws ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Long. Use int or Integer, or a typed getter from section 2.

Extract a List by Path

Goal: take the segments of every customer on a page into a list.

1
2
3
4
5
6
7
8
9
10
@Test
void extractAListByPath() {
    List<String> segments = consentsApi()
    .when()
        .get("/customers")
    .then()
        .extract().path("items.segment");

    assertTrue(segments.contains("BUSINESS"));
}

What’s happening:

  • A path that collects a field across a list, such as items.segment, returns a List.
  • contains("BUSINESS") is plain Java on the extracted list.

Checkpoint: run the class again. Two tests pass.

Read Several Parts of One Response

Keep the ExtractableResponse

Goal: create a customer once, and read its id, Location header, status and content type from the same response.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
void extractHeadersAndTheStatusCode() {
    ExtractableResponse<Response> created = consentsApi()
        .contentType(ContentType.JSON)
        .body(new NewCustomer("Pieter Post", "pieter@example.nl", "RETAIL"))
    .when()
        .post("/customers")
    .then()
        .statusCode(201)
        .extract();

    String id = created.path("id");
    assertEquals("/api/v1/customers/" + id, created.header("Location"));
    assertEquals(201, created.statusCode());
    assertTrue(created.contentType().startsWith("application/json"));
}

What’s happening:

  • extract() without a method call returns the ExtractableResponse itself, so you can keep it in a variable.
  • The request is sent once, and every read comes from the same response.
  • The test checks a rule between two values: the Location header must end with the id from the body.

Checkpoint: run the class again. Three tests pass.

Don’t send a request twice to read two values. Two chains that each extract one value send two requests, and the second may get a different answer: here, it would create a second customer. Keep the ExtractableResponse and read both values from it.

Extract the Whole Response

Goal: take the whole response, read it in several ways, and check it again.

1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void extractTheWholeResponse() {
    Response response = consentsApi()
    .when()
        .get("/customers/{id}", "cust-2")
    .then()
        .statusCode(200)
        .extract().response();

    assertEquals("Jan Jansen", response.path("name"));
    assertTrue(response.asString().contains("\"email\""));
    response.then().body("segment", equalTo("RETAIL"));
}

What’s happening:

  • extract().response() returns a Response with everything: path(..), headers, cookies and timing.
  • asString() returns the raw body as text.
  • response.then() starts a new validation chain on the same response, as in Take Apart a REST Assured Test.

Checkpoint: run the class again. Four tests pass.

Use a Value in the Next Request

Open the Second Customer on a Page

Goal: find a customer with one request and open it with the next.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
void aValueFromOneResponseInTheNextRequest() {
    String secondCustomerOnPage = consentsApi()
        .queryParam("size", 2)
    .when()
        .get("/customers")
    .then()
        .extract().path("items[1].id");

    consentsApi()
    .when()
        .get("/customers/{id}", secondCustomerOnPage)
    .then()
        .statusCode(200)
        .body("id", equalTo(secondCustomerOnPage));
}

What’s happening:

  • The first request reads a page of two and extracts the id of the second customer.
  • The second request opens that customer, and checks that it has the same id.
  • This is the simplest chain of requests. Section 5 builds a whole flow this way.

Checkpoint: run the class again. All five tests pass.

Don’t hard-code ids the server generates, such as cust-6. Other tests on the same server create customers too, so a new id, and even totalItems, depends on what ran first. Extract the id from the response, as these tests do.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-04 -Dtest=ExtractingValuesTest

You should see a result similar to the following:

1
2
3
4
5
6
[INFO] Running com.javanibble.module_04.section_01.ExtractingValuesTest
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.422 s -- in com.javanibble.module_04.section_01.ExtractingValuesTest
[INFO]
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Make a Test Fail

In extractOneValueByPath, change "cust-1" to "cust-99" and run the command again. You should see a result similar to the following:

1
2
3
[ERROR] Failures:
[ERROR]   ExtractingValuesTest.extractOneValueByPath:53 1 expectation failed.
Expected status code <200> but was <404>.

The failure is about the status code, on the line that checks it, because statusCode(200) runs before extract(). Without that check, the 404 body has no name, so path("name") returns null, and the test would fail later, for example with NullPointerException: Cannot invoke "String.length()" because "name" is null. That message points at your code, not at the missing customer.

Change "cust-99" back to "cust-1" and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
NullPointerException on an extracted valueThe response wasn’t checked, and the path found nothingCheck the status, and anything you rely on, before extract()
ClassCastException: class java.lang.Integer cannot be cast to class java.lang.LongThe variable’s type doesn’t match the type REST Assured readUse int or Integer for whole numbers
An assertion on a count or an id fails only when the whole class runsOther tests on the same server created dataExtract generated values, and avoid exact totals

Try It Yourself

Exercise 1: Read a Page Once

Add a test called aPageIsReadOnce that requests a page of two customers, checks the status, and keeps the ExtractableResponse. From it, extract the ids on the page, totalItems and totalPages. Check that the ids are cust-1 and cust-2, and that totalPages is totalItems divided by two, rounded up.

Hint

Start from extractHeadersAndTheStatusCode. Other tests may have created customers, so don’t assert an exact totalItems; check the rule between the two values instead. In Java, (totalItems + 1) / 2 rounds up.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
void aPageIsReadOnce() {
    ExtractableResponse<Response> page = consentsApi()
        .queryParam("size", 2)
    .when()
        .get("/customers")
    .then()
        .statusCode(200)
        .extract();

    List<String> ids = page.path("items.id");
    int totalItems = page.path("totalItems");
    int totalPages = page.path("totalPages");

    assertEquals(List.of("cust-1", "cust-2"), ids);
    assertEquals((totalItems + 1) / 2, totalPages);
}

Exercise 2: Follow the Location Header

Add a test called theLocationHeaderLeadsToTheNewCustomer. Create a BUSINESS customer called "Fatima El Amrani" with the email "fatima@example.nl", check for 201, and extract the Location header. Then request that location and check the customer’s name and segment.

Hint

extract().header("Location") returns a value such as /api/v1/customers/cust-6. The helper already sets the base path /api/v1, so strip it with location.substring(ConsentsApi.BASE_PATH.length()) before you send the request.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Test
void theLocationHeaderLeadsToTheNewCustomer() {
    String location = consentsApi()
        .contentType(ContentType.JSON)
        .body(new NewCustomer("Fatima El Amrani", "fatima@example.nl", "BUSINESS"))
    .when()
        .post("/customers")
    .then()
        .statusCode(201)
        .extract().header("Location");

    consentsApi()
    .when()
        .get(location.substring(ConsentsApi.BASE_PATH.length()))
    .then()
        .statusCode(200)
        .body("name", equalTo("Fatima El Amrani"))
        .body("segment", equalTo("BUSINESS"));
}

Summary

You built ExtractingValuesTest, which checks a response and then takes values out of it: a name, a list of segments, a new customer’s id and Location header, the whole response, and an id used in the next request. A missing customer now fails on the status check, not with a NullPointerException.

  • extract() ends the validation chain and returns an ExtractableResponse, so every check before it runs first.
  • extract().path(..) reads a value or a list with GPath, typed by the variable you assign it to; the types must match.
  • Keep the ExtractableResponse to read several parts of one response, such as the id and the Location header, without sending the request twice.
  • extract().response() returns the whole Response, which you can read as text or check again with then().
  • Validate first and extract second, and extract only what you need later; check the rest in the chain.

Here are the commands you used in this guide:

1
2
3
git clone https://github.com/javanibble/rest-assured-examples.git
cd rest-assured-examples
mvn test -pl module-04 -Dtest=ExtractingValuesTest

What’s Next

Next: continue with Read Many Values With JsonPath and XmlPath in REST Assured, which uses typed getters such as getInt(..) and getList(..), and reads JSON and XML that didn’t come from an HTTP call.

The code:

Go deeper:

Related guides:

This post is licensed under CC BY 4.0 by the author.