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.
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
- About 25 minutes
- JDK 26 or later
- Maven 3.9 or later
- An IDE (IntelliJ IDEA, VS Code or Eclipse)
- Knowledge: you can read single values, indexes and collected fields such as
accounts.id, as taught in Check Every Part of an HTTP Response, and send query parameters, from Send Query and Form Parameters in REST Assured.
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
JsonGPathTestin themodule-03test 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].idandtransactions[-1].id, as in Module 1. - A collected field:
transactions.idwalks 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,itis 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:
| Method | Path | Purpose |
|---|---|---|
GET | /accounts/{id}/transactions | One account’s transactions, optionally filtered by type |
GET | /categories | The 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:
| id | Date | Type | Amount | Counterparty | Category |
|---|---|---|---|---|---|
| tx-1 | 2026-03-01 | CREDIT | 2500.00 | Acme B.V. | SALARY |
| tx-2 | 2026-03-02 | DEBIT | -42.35 | Albert Heijn | GROCERIES |
| tx-3 | 2026-03-05 | DEBIT | -1100.00 | Woonstichting De Key | RENT |
| tx-4 | 2026-03-09 | DEBIT | -60.00 | Albert Heijn | GROCERIES |
| tx-5 | 2026-03-15 | DEBIT | -40.00 | NS Reizigers | TRANSPORT |
| tx-6 | 2026-03-20 | CREDIT | 150.00 | Belastingdienst | REFUND |
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,amountandcounterparty.name, which the closures filter and compare. Amounts are JSON numbers, and debits are negative.tags, a list inside each transaction, which makestransactions.tagsa 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:
TransactionsApiis 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/v1set.transactions()sends the transactions request foracc-1001and returns theValidatableResponsefromthen(), so most tests are onebody(..)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.findreturns one element, so the path can carry on into its fields:.counterparty.name.- When nothing matches,
findreturnsnull.
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..idafter 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
findwhen you meanfindAll.findreturns one transaction, so a list matcher after it checks the wrong thing:find { it.type == 'DEBIT' }withhasSize(4)fails, and theActualvalue 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:
itis 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, andevery { .. }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
.idor.counterparty.name. - Debits are negative, so
minfinds 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 throwsNo signature of method: amount == -42 .... Compare the text instead,find { it.amount.toString() == '-42.35' }, or use whole numbers, as infindAll { 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.tagshas six elements, one list of tags per transaction.flatten()turns the six lists into one list of tags, andunique()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-infoas 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(),codeorfind { .. }, starts at the root list. codecollects the code of every category, astransactions.iddid 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
| Symptom | Likely cause | Fix |
|---|---|---|
IllegalArgumentException: No signature of method: amount == -42 ... | A decimal number inside a closure was split on its dot | Compare with toString(), or use whole numbers |
Actual is a single map, such as {id=tx-2, ...}, for a list matcher | The path uses find, which returns one element | Use findAll |
Actual shows nested brackets, such as [[income], [food], ...] | The path returns a list of lists | Add flatten() |
Actual: null | A find closure matched nothing | Check 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 andfindAll { .. }every match; inside a closure,itis the current element.collect { .. }transforms each element, andany,every,maxandminanswer 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, andunique()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:
- The finished test class:
JsonGPathTest.java - The code and run commands for this module: Module 3 README
Go deeper:
- REST Assured Usage wiki, for JSON paths and GPath in
body(..). - Groovy GPath documentation, for the path language behind REST Assured.
Related guides:
- Check Every Part of an HTTP Response, where you first read indexes and collected fields.
- Read REST Assured Failure Messages, for reading the
ExpectedandActuallines of a path failure.
