β‘ Declarative Collection Querying & Groovy Closure Filtration in Java
In enterprise API automation, responses often return large, deeply nested collections containing hundreds of records. Extracting an entire payload into Java memory, writing procedural for loops, and applying manual conditional if statements to locate a single nested object adds unnecessary friction and creates brittle tests. REST Assured solves this by embedding Groovy's GPath engine directly into its JSON and XML path evaluators. Inspired by XPath, GPath evaluates closures dynamically against the parsed object graph using the implicit iterator keyword it. By combining filter operators (findAll for multiple matches, find for the first match), transformation operators (collect), and mathematical aggregation closures (max, min, sum), engineers can query and assert specific items within complex datasets in a single, expressive statement.
GROOVY GPATH PARSING PIPELINE IN REST ASSURED:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β RAW JSON WIRE ARRAY (Parsed by Jackson / Groovy JsonSlurper) β
β [ β
β {"id": "STU-101", "name": "Nikita", "credits": 16, "track": "AUTOMATION", "active": true}, β
β {"id": "STU-102", "name": "Aarav", "credits": 8, "track": "SDET", "active": false}, β
β {"id": "STU-103", "name": "Rohan", "credits": 20, "track": "AUTOMATION", "active": true} β
β ] β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β GROOVY GPATH EXPRESSION COMPILATION (io.restassured.path.json.JsonPath) β
β Expression: "data.findAll { it.credits >= 12 && it.active }.name" β
β βββ 1. Path Navigator: Navigates to root or nested collection property ('data') β
β βββ 2. Closure Scoper: Binds each element iteratively to implicit delegate 'it' β
β βββ 3. Boolean Predicate: Evaluates condition (it.credits >= 12 && it.active == true) β
β βββ 4. Property Projector: Collects '.name' attributes from matching items into List<String> β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββ
βΌ βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
β FILTERING CLOSURES β β AGGREGATION & TRANSFORMATION CLOSURES β
ββββββββββββββββββββββββββββββββββββββββββββββββ€ ββββββββββββββββββββββββββββββββββββββββββββββββ€
β β’ findAll { condition } βββΊ List of matches β β β’ max { it.property } βββΊ Max element / val β
β β’ find { condition } βββΊ First match / Mapβ β β’ min { it.property } βββΊ Min element / val β
β β’ collect { transform } βββΊ Transformed List β β β’ sum() βββΊ Numerical total β
ββββββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
findAll. Demonstrates querying students by criteria (e.g., enrolled credits threshold), projecting matching names into a List<String>, and validating collection contents with Hamcrest matchers.
package com.nikita.restassured.gpath;
import io.restassured.path.json.JsonPath;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class GPathFindAllTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Filter all students with credits >= 12 using findAll in BDD assertions")
public void testFindAllInlineAssertion() {
given()
.baseUri(BASE_URI)
.when()
.get("/students")
.then()
.statusCode(200)
// findAll returns all objects where credits >= 12; '.fullName' projects their names
.body("data.findAll { it.enrolledCredits >= 12 }.fullName",
hasItems("Nikita Sharma", "Rohan Verma"))
// Verify size of filtered subset
.body("data.findAll { it.enrolledCredits >= 12 }.size()", equalTo(2))
// Assert that filtered candidates do not contain lower-credit student
.body("data.findAll { it.enrolledCredits >= 12 }.fullName",
not(hasItem("Aarav Deshmukh")));
System.out.println("[β] findAll closure evaluated successfully within BDD body assertion.");
}
@Test(description = "Extract filtered sub-list into strongly typed Java List using JsonPath")
public void testExtractFindAllResults() {
JsonPath jsonPath = given()
.baseUri(BASE_URI)
.when()
.get("/students")
.then()
.statusCode(200)
.extract().jsonPath();
// Extract candidate IDs belonging strictly to ENTERPRISE_AUTOMATION track
List<String> automationStudentIds = jsonPath.getList(
"data.findAll { it.academicTrack == 'ENTERPRISE_AUTOMATION' }.id",
String.class
);
System.out.println("[*] Filtered Automation Student IDs: " + automationStudentIds);
Assert.assertFalse(automationStudentIds.isEmpty());
Assert.assertTrue(automationStudentIds.contains("STU-88219"));
}
}
find. Returns a single object (deserialized as a Map<String, Object>) or allows chained property traversal (e.g. find { condition }.email) without index lookups.
package com.nikita.restassured.gpath;
import io.restassured.path.json.JsonPath;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class GPathFindSingleTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Locate single candidate by unique email and assert property inline")
public void testFindSingleElementInline() {
given()
.baseUri(BASE_URI)
.when()
.get("/students")
.then()
.statusCode(200)
// find locates the first matching object; immediate property read: .academicTrack
.body("data.find { it.email == 'nikita.sharma@nikita-infotech.com' }.academicTrack",
equalTo("ENTERPRISE_AUTOMATION"))
.body("data.find { it.id == 'STU-88219' }.enrolledCredits", equalTo(16));
System.out.println("[β] find { ... } closure isolated single record and verified attributes.");
}
@Test(description = "Extract entire matching JSON object into Java Map via find")
public void testExtractSingleRecordAsMap() {
JsonPath jsonPath = given()
.baseUri(BASE_URI)
.when()
.get("/students")
.then()
.statusCode(200)
.extract().jsonPath();
// Extract matching object as Map
Map<String, Object> studentRecord = jsonPath.get(
"data.find { it.id == 'STU-88219' }"
);
System.out.println("---------------- ISOLATED CANDIDATE RECORD ----------------");
studentRecord.forEach((k, v) -> System.out.println(" " + k + " = " + v));
System.out.println("-----------------------------------------------------------");
Assert.assertEquals(studentRecord.get("fullName"), "Nikita Sharma");
Assert.assertEquals(studentRecord.get("enrolledCredits"), 16);
}
}
&& (AND), || (OR), and ! (NOT) operators across nested numeric, boolean, and string fields.
package com.nikita.restassured.gpath;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class GPathCompoundPredicatesTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Filter records using compound logical operators: AND (&&), OR (||), and NOT (!)")
public void testCompoundPredicatesInClosures() {
given()
.baseUri(BASE_URI)
.when()
.get("/students")
.then()
.statusCode(200)
// 1. Logical AND (&&): Active students enrolled in ENTERPRISE_AUTOMATION with credits >= 12
.body("data.findAll { it.isActive == true && it.academicTrack == 'ENTERPRISE_AUTOMATION' && it.enrolledCredits >= 12 }.id",
hasItem("STU-88219"))
// 2. Logical OR (||): Students enrolled in either FULLSTACK_SDET or CLOUD_DEVOPS_QA
.body("data.findAll { it.academicTrack == 'FULLSTACK_SDET' || it.academicTrack == 'CLOUD_DEVOPS_QA' }.size()",
greaterThanOrEqualTo(1))
// 3. Logical NOT (!): Exclude suspended or inactive students
.body("data.findAll { !it.isActive }.size()", equalTo(0))
// 4. Combined complex logic with grouping parentheses
.body("data.findAll { (it.enrolledCredits > 10 || it.gpa >= 3.8) && it.isActive }.fullName",
hasItem("Nikita Sharma"));
System.out.println("[β] Compound boolean predicates (&&, ||, !) evaluated successfully in GPath.");
}
}
collect. Applies inline string modifications, formats labels, performs calculations, and produces transformed List collections directly within the query.
package com.nikita.restassured.gpath;
import io.restassured.path.json.JsonPath;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.hasItem;
public class GPathCollectTransformationTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Transform student names to uppercase and format display tags via collect")
public void testCollectTransformation() {
given()
.baseUri(BASE_URI)
.when()
.get("/students")
.then()
.statusCode(200)
// collect applies the transformation closure to every element in the collection:
.body("data.collect { it.fullName.toUpperCase() }",
hasItem("NIKITA SHARMA"))
// Format composite string labels on the fly:
.body("data.collect { it.id + '::' + it.academicTrack }",
hasItem("STU-88219::ENTERPRISE_AUTOMATION"));
System.out.println("[β] collect transformation closures executed successfully in BDD assertions.");
}
@Test(description = "Extract calculated tuition fees using collect closure into Java List")
public void testExtractTransformedValues() {
JsonPath jsonPath = given()
.baseUri(BASE_URI)
.when()
.get("/students")
.then()
.statusCode(200)
.extract().jsonPath();
// Calculate tuition fee dynamically: enrolledCredits * 1500 INR
List<Integer> calculatedTuitions = jsonPath.getList(
"data.collect { it.enrolledCredits * 1500 }",
Integer.class
);
System.out.println("[*] Calculated Tuitions: " + calculatedTuitions);
Assert.assertFalse(calculatedTuitions.isEmpty());
// 16 credits * 1500 = 24000
Assert.assertTrue(calculatedTuitions.contains(24000));
}
}
max), minimums (min), totals (sum), and custom aggregations without looping over array indices.
package com.nikita.restassured.gpath;
import io.restassured.path.json.JsonPath;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
public class GPathAggregationsTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Assert maximum, minimum, and total sums using Groovy GPath aggregations")
public void testNumericAggregationsInline() {
given()
.baseUri(BASE_URI)
.when()
.get("/students")
.then()
.statusCode(200)
// 1. max(): Finds the highest scalar value in the numeric collection
.body("data.enrolledCredits.max()", equalTo(20))
// 2. min(): Finds the lowest scalar value in the numeric collection
.body("data.enrolledCredits.min()", equalTo(8))
// 3. sum(): Calculates the numerical total of all collection elements
// 16 + 8 + 20 = 44
.body("data.enrolledCredits.sum()", equalTo(44))
// 4. Assert sum against relational boundaries
.body("data.enrolledCredits.sum()", greaterThan(40));
System.out.println("[β] GPath aggregations (max, min, sum) verified within BDD assertions.");
}
@Test(description = "Locate the entire record containing the maximum credits via max closure")
public void testFindRecordWithMaxCredits() {
JsonPath jsonPath = given()
.baseUri(BASE_URI)
.when()
.get("/students")
.then()
.statusCode(200)
.extract().jsonPath();
// max { closure } returns the entire object containing the highest property value:
Map<String, Object> topCreditStudent = jsonPath.get(
"data.max { it.enrolledCredits }"
);
System.out.println("[*] Top Credit Candidate Record: " + topCreditStudent);
Assert.assertEquals(topCreditStudent.get("enrolledCredits"), 20);
Assert.assertEquals(topCreditStudent.get("fullName"), "Rohan Verma");
}
}
package com.nikita.restassured.gpath;
import io.restassured.path.json.JsonPath;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.hasItem;
public class GPathNestedArrayFilteringTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Filter parent students based on attributes inside nested course arrays")
public void testNestedArrayFiltering() {
// Sample nested structure in response:
// {
// "data": [
// { "id": "STU-88219", "name": "Nikita", "courses": [ {"code": "REST-JAVA", "credits": 4} ] },
// { "id": "STU-88220", "name": "Aarav", "courses": [ {"code": "PYTHON-QA", "credits": 3} ] }
// ]
// }
given()
.baseUri(BASE_URI)
.when()
.get("/students/hierarchical-catalog")
.then()
.statusCode(200)
// Query students who have ANY course with code 'REST-JAVA':
.body("data.findAll { it.courses.code.contains('REST-JAVA') }.name",
hasItem("Nikita"))
// Query students whose total course credits within their nested array exceed 3:
.body("data.findAll { it.courses.credits.sum() >= 4 }.id",
hasItem("STU-88219"));
System.out.println("[β] Nested child array conditions evaluated against parent entities.");
}
@Test(description = "Extract distinct course codes across all students using flatten()")
public void testExtractFlattenedChildArrays() {
JsonPath jsonPath = given()
.baseUri(BASE_URI)
.when()
.get("/students/hierarchical-catalog")
.then()
.statusCode(200)
.extract().jsonPath();
// data.courses.code returns a nested List>.
// Applying .flatten() collapses nested collections into a single flat List:
List<String> allEnrolledCoursesFlat = jsonPath.getList(
"data.courses.code.flatten()",
String.class
);
System.out.println("[*] Flattened Course Codes: " + allEnrolledCoursesFlat);
Assert.assertFalse(allEnrolledCoursesFlat.isEmpty());
Assert.assertTrue(allEnrolledCoursesFlat.contains("REST-JAVA"));
}
}
startsWith(), endsWith(), contains(), and regex pattern matching directly inside filter expressions.
package com.nikita.restassured.gpath;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class GPathStringClosuresTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Filter records using Groovy string methods inside closures")
public void testStringMethodsInsideClosures() {
given()
.baseUri(BASE_URI)
.when()
.get("/students")
.then()
.statusCode(200)
// 1. startsWith() within closure
.body("data.findAll { it.id.startsWith('STU-88') }.fullName",
hasItem("Nikita Sharma"))
// 2. endsWith() within closure: Match institutional corporate emails
.body("data.findAll { it.email.endsWith('@nikita-infotech.com') }.size()",
greaterThanOrEqualTo(2))
// 3. length() comparison within closure
.body("data.findAll { it.fullName.length() > 10 }.id",
hasItems("STU-88219", "STU-88220"))
// 4. Groovy regex match operator (=~): Matches phone numbers with country code +91
.body("data.findAll { it.contactInfo.phone =~ /\\+91-.*/ }.size()",
greaterThan(0));
System.out.println("[β] String functions (startsWith, endsWith, length, regex) evaluated inside GPath closures.");
}
}
?. safe-navigation operator), and missing delegation keywords.
package com.nikita.restassured.gpath;
import io.restassured.path.json.JsonPath;
import org.testng.Assert;
import org.testng.annotations.Test;
public class GPathDebuggingTest {
// ==========================================================================
// PITFALL 1: PROPERTY NAMES CONTAINING HYPHENS (e.g., "enrolled-credits")
// In Groovy, hyphens are treated as subtraction operators (it.enrolled - credits)!
// SOLUTION: Wrap hyphenated property names in quotes: it.'enrolled-credits'
// ==========================================================================
@Test(description = "Demonstrate handling of hyphenated property names in GPath")
public void testHyphenatedPropertyEscaping() {
String jsonWithHyphens = "{\n" +
" \"students\": [\n" +
" { \"student-id\": \"STU-101\", \"enrolled-credits\": 16 },\n" +
" { \"student-id\": \"STU-102\", \"enrolled-credits\": 8 }\n" +
" ]\n" +
"}";
JsonPath jsonPath = new JsonPath(jsonWithHyphens);
// Correct syntax: wrap property in single quotes
String id = jsonPath.getString("students.find { it.'enrolled-credits' > 10 }.'student-id'");
System.out.println("[+] Escaped hyphen property extracted ID: " + id);
Assert.assertEquals(id, "STU-101");
}
// ==========================================================================
// PITFALL 2: NULL POINTERS IN OPTIONAL NESTED NODES
// If some objects lack a nested object, it.contact.city throws NullPointerException.
// SOLUTION: Use the Groovy Safe-Navigation operator: it.contact?.city
// ==========================================================================
@Test(description = "Demonstrate Groovy safe navigation operator (?.) to prevent NPEs")
public void testSafeNavigationOperator() {
String jsonWithSparseNodes = "{\n" +
" \"users\": [\n" +
" { \"id\": 1, \"contact\": { \"city\": \"Pune\" } },\n" +
" { \"id\": 2, \"contact\": null },\n" +
" { \"id\": 3 }\n" +
" ]\n" +
"}";
JsonPath jsonPath = new JsonPath(jsonWithSparseNodes);
// Using safe navigation 'it.contact?.city' skips nulls without throwing exceptions:
int puneUserCount = jsonPath.getInt("users.findAll { it.contact?.city == 'Pune' }.size()");
System.out.println("[+] Users located in Pune (safe navigation): " + puneUserCount);
Assert.assertEquals(puneUserCount, 1);
}
}
GROOVY GPATH EXPRESSION SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β OPERATION / CLOSURE β GPATH SYNTAX PATTERN β RETURN TYPE β PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Filter All Matches β collection.findAll { cond } β java.util.List β Filters all elements matching β
β Locate First Match β collection.find { cond } β Map / Object β Returns first matching elementβ
β Transform Elements β collection.collect { trans } β java.util.List β Applies projection / mapping β
β Maximum Scalar Value β collection.property.max() β Numeric / Compar.β Finds highest property value β
β Object with Max Value β collection.max { it.prop } β Map<String, Obj> β Returns object with max prop β
β Minimum Scalar Value β collection.property.min() β Numeric / Compar.β Finds lowest property value β
β Object with Min Value β collection.min { it.prop } β Map<String, Obj> β Returns object with min prop β
β Numerical Sum Total β collection.property.sum() β Numeric (Total) β Adds all numeric values in colβ
β Flatten Nested Arrays β collection.property.flatten()β Flattened List β Collapses List<List<T>> to Listβ
β Safe Navigation β it.nested?.property β Null-Safe Value β Prevents NPEs on missing nodesβ
β Hyphenated Property β it.'hyphenated-property' β Property Value β Escapes Groovy arithmetic sub β
β Regex Matcher Operator β it.property =~ /regex/ β Boolean (Match) β Evaluates inline regex patternβ
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 GROOVY GPATH BEST PRACTICES: β
β 1. Always use safe navigation (?.) on optional nodes: Prevent NPEs when querying sparse JSON schemas. β
β 2. Escape hyphenated keys with single quotes: it.'enrolled-credits' prevents Groovy subtraction bugs. β
β 3. Use find for uniqueness, findAll for multi-items: find returns a single Map, avoiding [0] indexing. β
β 4. Combine GPath with Hamcrest in .body(): Avoid extracting to Java memory when checking collections. β
β 5. Use max { it.prop } to fetch the whole object: Don't settle for just the scalar when you need data. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ