Post

Filter JSON Lists With GPath in REST Assured

Filter and transform JSON lists with Groovy closures, covering find, findAll, collect, any and every, max and min, indexes and ranges, flattening, keys with dashes and a JSON array at the root.

Filter JSON Lists With GPath in REST Assured

Your statement test needs to know which counterparty received the rent. So it extracts the whole transaction list, loops over it in Java, compares each category, and asserts on what it found: fifteen lines for one fact. In this guide, you’ll answer questions like that in one line inside body(..), with GPath closures that filter, transform and test a JSON list.

Level: Intermediate · Time: 25 minutes · Part of: Module 3: Validating Responses in Depth, section 1

What You’ll Build

You’ll build a test class called JsonGPathTest with 11 tests. Each one checks the same month of transactions with a different GPath feature: finding, filtering, collecting, comparing, slicing and flattening.

Most tests send this request and check this response:

1
2
3
4
5
6
7
GET /api/v1/accounts/acc-1001/transactions HTTP/1.1
Host: localhost:<port>

HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8

{"accountId":"acc-1001","transactions":[{"id":"tx-1","type":"CREDIT","amount":2500.00, ...}, ...]}

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

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

In this guide, you will:

  • Filter a list.
  • Transform and test a list.
  • Slice and flatten lists.
  • Read keys with a dash.
  • Let the server filter.
  • Read a JSON array at the root.

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 3, so you start from scratch. Create JsonGPathTest in the module-03 test sources and follow every heading below.
  • Skip ahead: open the finished class (JsonGPathTest.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 root paths that shorten repeated paths, or reading amounts as BigDecimal; they’re taught in section 2 and section 3.

Understand GPath

The problem. A path such as transactions[0].id reads one value, and transactions.id collects one field from every element. Real checks are often more specific: which element matches a condition, whether every element follows a rule, which one is the largest. Extracting the list and looping in Java answers them, but it hides a one-line fact behind a dozen lines of code.

The concept. GPath is the path language of Groovy, and REST Assured 6 still evaluates it with Groovy. So a path can do more than walk into fields:

  • A field or an index: iban, transactions[0].id and transactions[-1].id, as in Module 1.
  • A collected field: transactions.id walks into every element and returns a list of ids.
  • A closure in braces: transactions.findAll { it.type == 'DEBIT' } runs the code in braces for each element. Inside it, it is the current element.
  • A Groovy method: size(), unique(), flatten() and others work on any list in the path.

Strings inside a closure use single quotes, so the path still fits in a Java string without escaping.

When to use it. Use GPath when a check is one fact about a list, such as “the rent went to Woonstichting De Key”. When you need several values for further Java logic, extract them instead, as Module 4 shows. When the API can filter for you, test that too.

Ask the list a question in the path, not in a loop.

Meet the API Under Test

Module 3 tests a Transactions API. 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 guide uses two of them:

MethodPathPurpose
GET/accounts/{id}/transactionsOne account’s transactions, optionally filtered by type
GET/categoriesThe transaction categories, as a JSON array at the root

The API serves one account, acc-1001, with six transactions that never change, so tests can assert exact values:

idDateTypeAmountCounterpartyCategory
tx-12026-03-01CREDIT2500.00Acme B.V.SALARY
tx-22026-03-02DEBIT-42.35Albert HeijnGROCERIES
tx-32026-03-05DEBIT-1100.00Woonstichting De KeyRENT
tx-42026-03-09DEBIT-60.00Albert HeijnGROCERIES
tx-52026-03-15DEBIT-40.00NS ReizigersTRANSPORT
tx-62026-03-20CREDIT150.00BelastingdienstREFUND

GET /api/v1/accounts/acc-1001/transactions returns a response similar to the following, shortened to the first transaction:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8

{
    "accountId": "acc-1001",
    "iban": "NL91ABNA0417164300",
    "currency": "EUR",
    "balance": { "opening": 1000.00, "closing": 2407.65 },
    "transactions": [
        {
            "id": "tx-1",
            "bookingDate": "2026-03-01",
            "type": "CREDIT",
            "amount": 2500.00,
            "counterparty": { "iban": "NL02ABNA0123456789", "name": "Acme B.V." },
            "category": "SALARY",
            "tags": ["income"],
            "remittance-info": "Salary March"
        },
        ...
    ]
}

GET /api/v1/categories returns a list, not an object:

1
2
3
4
5
6
7
[
    { "label": "Salary", "code": "SALARY" },
    { "label": "Groceries", "code": "GROCERIES" },
    { "label": "Rent", "code": "RENT" },
    { "label": "Transport", "code": "TRANSPORT" },
    { "label": "Refund", "code": "REFUND" }
]

Your tests check these fields:

  • type, category, amount and counterparty.name, which the closures filter and compare. Amounts are JSON numbers, and debits are negative.
  • tags, a list inside each transaction, which makes transactions.tags a list of lists.
  • remittance-info, a key with a dash in it, on purpose.

Filter a List

Set Up the Test Class

Goal: create the test class, start the Transactions API and add a helper that returns the checked response.

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
40
41
package com.javanibble.module_03.section_01;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;

import com.javanibble.transactions.TransactionsApi;

import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;

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

class JsonGPathTest {

    private static TransactionsApi api;

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

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

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

    private static ValidatableResponse transactions() {
        return transactionsApi().when().get("/accounts/{id}/transactions", TransactionsApi.ACCOUNT_ID).then();
    }
}

What’s happening:

  • TransactionsApi is Module 3’s test server. It starts and stops like the APIs of the earlier modules.
  • transactionsApi() returns a request with the base URI, port and base path /api/v1 set.
  • transactions() sends the transactions request for acc-1001 and returns the ValidatableResponse from then(), so most tests are one body(..) call.

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

Find the First Match

Goal: find the rent transaction and read its counterparty.

1
2
3
4
5
@Test
void findReturnsTheFirstMatch() {
    transactions().body("transactions.find { it.category == 'RENT' }.counterparty.name",
            equalTo("Woonstichting De Key"));
}

What’s happening:

  • find { .. } runs the closure for each transaction and returns the first one for which it’s true.
  • find returns one element, so the path can carry on into its fields: .counterparty.name.
  • When nothing matches, find returns null.

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

Find Every Match

Goal: collect the ids of every debit.

1
2
3
4
5
@Test
void findAllReturnsEveryMatch() {
    transactions().body("transactions.findAll { it.type == 'DEBIT' }.id",
            contains("tx-2", "tx-3", "tx-4", "tx-5"));
}

What’s happening:

  • findAll { .. } returns a list of every element for which the closure is true.
  • .id after it collects the id of every match, in order.
  • When nothing matches, the list is empty.

Checkpoint: run the class again. Two tests pass.

Don’t use find when you mean findAll. find returns one transaction, so a list matcher after it checks the wrong thing: find { it.type == 'DEBIT' } with hasSize(4) fails, and the Actual value is a single map, {id=tx-2, ...}.

Look Into Nested Objects

Goal: count the transactions with one counterparty.

1
2
3
4
@Test
void conditionsCanLookIntoNestedObjects() {
    transactions().body("transactions.findAll { it.counterparty.name == 'Albert Heijn' }.size()", equalTo(2));
}

What’s happening:

  • it is a whole transaction, so the condition can use any field in it, at any depth.
  • .size() counts the matches.
  • A dot inside a quoted string, as in 'Acme B.V.', is part of the string, not a step in the path.

Checkpoint: run the class again. Three tests pass.

Transform and Test a List

Transform Every Element

Goal: count the distinct counterparties.

1
2
3
4
@Test
void collectTransformsEveryElement() {
    transactions().body("transactions.collect { it.counterparty.name }.unique().size()", equalTo(5));
}

What’s happening:

  • collect { .. } turns each element into the value of the closure: here, the counterparty name.
  • unique() removes the second Albert Heijn, which leaves five names.

Checkpoint: run the class again. Four tests pass.

Ask Whether Any or Every Element Matches

Goal: check one fact about some elements and one about all of them.

1
2
3
4
5
6
@Test
void anyAndEvery() {
    transactions()
        .body("transactions.any { it.category == 'RENT' }", is(true))
        .body("transactions.every { it.id.startsWith('tx-') }", is(true));
}

What’s happening:

  • any { .. } is true when at least one element matches, and every { .. } when all of them do.
  • A closure can call Java methods on the values, such as startsWith(..) on a string.

Checkpoint: run the class again. Five tests pass.

Find the Largest and Smallest

Goal: find the transaction with the highest amount and the one with the lowest.

1
2
3
4
5
6
@Test
void maxAndMinCompareByAClosure() {
    transactions()
        .body("transactions.max { it.amount }.id", equalTo("tx-1"))
        .body("transactions.min { it.amount }.counterparty.name", equalTo("Woonstichting De Key"));
}

What’s happening:

  • max { it.amount } compares the elements by the closure’s value and returns the whole element with the highest amount, not the amount itself.
  • That’s why the path can go on to .id or .counterparty.name.
  • Debits are negative, so min finds the largest debit: the rent.

Checkpoint: run the class again. Six tests pass.

Don’t compare decimals inside a closure. REST Assured splits a path on its dots, so find { it.amount == -42.35 } breaks apart and throws No signature of method: amount == -42 .... Compare the text instead, find { it.amount.toString() == '-42.35' }, or use whole numbers, as in findAll { it.amount < -50 }.

Slice and Flatten Lists

Use Indexes and Ranges

Goal: read elements by position, from the start and from the end.

1
2
3
4
5
6
7
8
@Test
void indexesAndRanges() {
    transactions()
        .body("transactions[0].id", equalTo("tx-1"))
        .body("transactions[-1].id", equalTo("tx-6"))
        .body("transactions[0..1].id", contains("tx-1", "tx-2"))
        .body("transactions[-2..-1].id", contains("tx-5", "tx-6"));
}

What’s happening:

  • A negative index counts from the end: [-1] is the last element.
  • A range such as [0..1] includes both ends, so it returns two elements.
  • Negative ranges work too: [-2..-1] is the last two elements.

Checkpoint: run the class again. Seven tests pass.

Flatten a List of Lists

Goal: check the tags used across all transactions.

Each transaction has its own list of tags, so transactions.tags is a list of lists:

1
2
3
4
5
6
@Test
void listsOfListsCanBeFlattened() {
    transactions()
        .body("transactions.tags", hasSize(6))
        .body("transactions.tags.flatten().unique()", hasItems("income", "food", "housing", "tax"));
}

What’s happening:

  • transactions.tags has six elements, one list of tags per transaction.
  • flatten() turns the six lists into one list of tags, and unique() removes the duplicates.
  • Without flatten(), the check fails, as you’ll see in Make a Test Fail.

Checkpoint: run the class again. Eight tests pass.

Read Keys With a Dash

Read remittance-info

Goal: read a key that contains a dash.

1
2
3
4
5
6
@Test
void keysWithADash() {
    transactions()
        .body("transactions[0].remittance-info", equalTo("Salary March"))
        .body("transactions[0].'remittance-info'", equalTo("Salary March"));
}

What’s happening:

  • REST Assured reads remittance-info as a key, even without quotes.
  • Quoting it, as in 'remittance-info', makes clear that the dash is part of the name, as in the echo paths of Send Headers and Cookies in REST Assured.

Checkpoint: run the class again. Nine tests pass.

Let the Server Filter

Filter With a Query Parameter

Goal: ask the API for credits only, and check that the filter is right.

GPath filters the response on the client. When an API can filter for you, test that too:

1
2
3
4
5
6
7
8
9
10
@Test
void theServerCanFilterToo() {
    transactionsApi()
        .queryParam("type", "credit")
    .when()
        .get("/accounts/{id}/transactions", TransactionsApi.ACCOUNT_ID)
    .then()
        .body("transactions.type", everyItem(equalTo("CREDIT")))
        .body("transactions.id", contains("tx-1", "tx-6"));
}

What’s happening:

  • queryParam("type", "credit") asks the API to filter; it accepts the type in any case.
  • everyItem(..) proves that every returned transaction is a credit.
  • contains("tx-1", "tx-6") proves that none is missing.

Checkpoint: run the class again. Ten tests pass.

Read a JSON Array at the Root

Check the Categories List

Goal: check a body that’s a list, not an object.

1
2
3
4
5
6
7
8
9
10
11
@Test
void aJsonArrayAtTheRoot() {
    transactionsApi()
    .when()
        .get("/categories")
    .then()
        .body("$", hasSize(5))
        .body("size()", equalTo(5))
        .body("code", hasItems("SALARY", "RENT"))
        .body("find { it.code == 'RENT' }.label", equalTo("Rent"));
}

What’s happening:

  • "$" is the whole body. On a root array, "" works as well.
  • A path without a list name, such as size(), code or find { .. }, starts at the root list.
  • code collects the code of every category, as transactions.id did for transactions.

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

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-03 -Dtest=JsonGPathTest

You should see a result similar to the following:

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

Make a Test Fail

In listsOfListsCanBeFlattened, remove .flatten() from the second path, so it reads "transactions.tags.unique()", and run the command again. You should see a result similar to the following:

1
2
3
4
5
[ERROR] Failures:
[ERROR]   JsonGPathTest.listsOfListsCanBeFlattened:105 1 expectation failed.
JSON path transactions.tags.unique() doesn't match.
Expected: (a collection containing "income" and a collection containing "food" and a collection containing "housing" and a collection containing "tax")
  Actual: <[[income], [food], [housing, fixed], [travel], [income, tax]]>

The message repeats the path you wrote, and the nested brackets in Actual show why it failed: the elements are lists, not tags. unique() still ran, and removed the second [food] list, but no list equals the string "food".

Put .flatten() back and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
IllegalArgumentException: No signature of method: amount == -42 ...A decimal number inside a closure was split on its dotCompare with toString(), or use whole numbers
Actual is a single map, such as {id=tx-2, ...}, for a list matcherThe path uses find, which returns one elementUse findAll
Actual shows nested brackets, such as [[income], [food], ...]The path returns a list of listsAdd flatten()
Actual: nullA find closure matched nothingCheck the condition and the case of its values

Try It Yourself

Exercise 1: Name the Payers

Add a test called creditsComeFromTwoCounterparties that collects the counterparty names of every credit, in order, with one path.

Hint

Start from findAllReturnsEveryMatch. Change the condition to credits, and walk into .counterparty.name instead of .id.

Solution
1
2
3
4
5
@Test
void creditsComeFromTwoCounterparties() {
    transactions().body("transactions.findAll { it.type == 'CREDIT' }.counterparty.name",
            contains("Acme B.V.", "Belastingdienst"));
}

Exercise 2: Check the Large Debits

Add a test called largeDebitsAndGroceries that checks three facts in one chain: the ids of the transactions below -50 are tx-3 and tx-4; every debit has a negative amount; and all grocery transactions went to one counterparty, Albert Heijn.

Hint

Use whole numbers in the closures, as the decimal warning explains. You can chain every { .. } after findAll { .. }, and unique() after a collected field.

Solution
1
2
3
4
5
6
7
8
@Test
void largeDebitsAndGroceries() {
    transactions()
        .body("transactions.findAll { it.amount < -50 }.id", contains("tx-3", "tx-4"))
        .body("transactions.findAll { it.type == 'DEBIT' }.every { it.amount < 0 }", is(true))
        .body("transactions.findAll { it.category == 'GROCERIES' }.counterparty.name.unique()",
                contains("Albert Heijn"));
}

Summary

You built JsonGPathTest, which filters, transforms, slices and flattens a month of transactions with GPath, reads keys with dashes and a JSON array at the root, and checks the server’s own filter. Which counterparty received the rent is now one line.

  • find { .. } returns the first match and findAll { .. } every match; inside a closure, it is the current element.
  • collect { .. } transforms each element, and any, every, max and min answer questions about the whole list.
  • Indexes can count from the end, and ranges such as [0..1] include both ends.
  • flatten() turns a list of lists into one list, and unique() removes duplicates.
  • $ is the root, also when the body itself is an array; avoid decimal numbers inside closures.

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-03 -Dtest=JsonGPathTest

What’s Next

Next: continue with Shorten JSON Paths With Root Paths in REST Assured, which shortens repeated paths and puts values into a path from Java.

The code:

Go deeper:

Related guides:

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