GROOVY GPATH JSON FILTERING: FIND, FINDALL, COLLECT, MAX & MIN

Architect advanced in-memory query pipelines in REST Assured: Groovy GPath compilation, filtering collections with find() and findAll(), transforming payloads via collect(), mathematical aggregations (max, min, sum), nested property projections, and conditional multi-attribute closures.

⚑ 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.

1. Groovy GPath Expression Engine & Closure Architecture
The internal architecture of Groovy GPath execution within REST Assured, tracing how JSON wire strings are parsed into abstract syntax trees, evaluated through dynamic closures, and projected into target Java collections.
Groovy GPath Closure Pipeline & AST Evaluation Topography
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    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Architectural Standard: In Groovy GPath expressions, the keyword 'it' represents the current iteration item inside the closure curly braces { it.property == value }. If property names contain hyphens or spaces, wrap the key in quotes: it.'enrolled-credits' > 10.
Real-Time Example 1: Filtering All Matching Elements via findAll { condition }
Filtering collections with 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.
Java (findAll Collection Filtering & Property Projection)
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"));
    }
}
findAll Evaluation Output: GET /v1/students -> HTTP 200 OK [118ms] Filtered data.findAll { it.enrolledCredits >= 12 }.fullName ──► ["Nikita Sharma", "Rohan Verma"] Filtered data.findAll { it.academicTrack == 'ENTERPRISE_AUTOMATION' }.id ──► ["STU-88219", "STU-88221"] PASSED: testFindAllInlineAssertion PASSED: testExtractFindAllResults
Real-Time Example 2: Locating a Single Record via find { condition }
Locating the first matching element using find. Returns a single object (deserialized as a Map<String, Object>) or allows chained property traversal (e.g. find { condition }.email) without index lookups.
Java (find Single Object Extraction & Field Navigation)
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);
    }
}
find Extraction Output: GET /v1/students -> HTTP 200 OK [74ms] ---------------- ISOLATED CANDIDATE RECORD ---------------- id = STU-88219 fullName = Nikita Sharma email = nikita.sharma@nikita-infotech.com academicTrack = ENTERPRISE_AUTOMATION enrolledCredits = 16 isActive = true -----------------------------------------------------------
Real-Time Example 3: Multi-Conditional Predicates (Boolean AND, OR, NOT)
Combining multiple filter conditions within GPath closures. Demonstrates building compound criteria using && (AND), || (OR), and ! (NOT) operators across nested numeric, boolean, and string fields.
Java (Compound Boolean Predicates in GPath Closures)
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.");
    }
}
Compound Predicate Trace: Predicate (isActive == true && track == 'ENTERPRISE_AUTOMATION' && credits >= 12) ──► Matched: ["STU-88219"] Predicate (!it.isActive) ──► Empty list: 0 records Parenthesized Grouping ((credits > 10 || gpa >= 3.8) && isActive) ──► Matched: "Nikita Sharma" PASSED: testCompoundPredicatesInClosures
Real-Time Example 4: Transforming Collections via collect { transformation }
Transforming payload representations using collect. Applies inline string modifications, formats labels, performs calculations, and produces transformed List collections directly within the query.
Java (Collection Transformation & Mapping via collect)
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));
    }
}
Transformation Telemetry: Transformed uppercase names: ["NIKITA SHARMA", "AARAV DESHMUKH", "ROHAN VERMA"] Composite tag projection: ["STU-88219::ENTERPRISE_AUTOMATION", "STU-88220::FULLSTACK_SDET"] Calculated Tuitions (credits * 1500): [24000, 12000, 30000] PASSED: testCollectTransformation
Real-Time Example 5: Mathematical Aggregations: max(), min(), sum() & average()
Performing mathematical aggregation on numeric collections. Evaluates maximums (max), minimums (min), totals (sum), and custom aggregations without looping over array indices.
Java (Statistical & Numeric Aggregations: max, min, sum)
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");
    }
}
Aggregation Execution Output: GET /v1/students -> HTTP 200 OK [86ms] Calculated data.enrolledCredits.max() ──► 20 Calculated data.enrolledCredits.min() ──► 8 Calculated data.enrolledCredits.sum() ──► 44 Top credit candidate object extracted: {id=STU-103, fullName=Rohan Verma, enrolledCredits=20} PASSED: testNumericAggregationsInline
Real-Time Example 6: Deep Filtering on Hierarchical & Nested Arrays
Filtering across nested object hierarchies. Demonstrates querying students who possess a specific sub-item within a nested child array (e.g. searching students enrolled in a specific course code).
Java (Hierarchical Child Collection Filtering)
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"));
    }
}
Nested Filtering Telemetry: GET /v1/students/hierarchical-catalog -> HTTP 200 OK [132ms] Parent filter: data.findAll { it.courses.code.contains('REST-JAVA') } ──► ["Nikita"] Flattened child array extraction: ["REST-JAVA", "DOCKER-QA", "PYTHON-QA", "K8S-DEVOPS"] PASSED: testNestedArrayFiltering
Real-Time Example 7: GPath Closures with String & Regular Expression Methods
Leveraging Groovy's string manipulation methods inside GPath closures. Uses startsWith(), endsWith(), contains(), and regex pattern matching directly inside filter expressions.
Java (String Functions & Pattern Matching in GPath Closures)
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.");
    }
}
String Closure Evaluation: Matched it.id.startsWith('STU-88') ──► ["Nikita Sharma"] Matched it.email.endsWith('@nikita-infotech.com') ──► Count: 3 Matched it.fullName.length() > 10 ──► ["STU-88219", "STU-88220"] Matched it.contactInfo.phone =~ /\+91-.*/ ──► Count: 2 PASSED: testStringMethodsInsideClosures
Real-Time Example 8: Debugging & Diagnosing Broken GPath Syntax
Troubleshooting common GPath pitfalls: handling hyphens in property names, unclosed closure braces, null pointer safety navigation (?. safe-navigation operator), and missing delegation keywords.
Java (GPath Pitfalls, Safe Navigation & Syntax Triage)
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);
    }
}
Debugging & Safe Navigation Output: [+] Escaped hyphen property extracted ID: STU-101 (Avoided Groovy subtraction error) [+] Users located in Pune (safe navigation): 1 (Avoided NullPointerException on sparse nodes) PASSED: testHyphenatedPropertyEscaping PASSED: testSafeNavigationOperator
Real-Time Example 9: Groovy GPath Specification Reference Matrix
A comprehensive reference summary pairing GPath operations, syntax expressions, return types, and operational best practices for REST Assured engineers.
Groovy GPath Expression Specification Reference Matrix
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.    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Best Practice: Groovy GPath expressions elevate REST Assured from a simple HTTP client to a declarative query platform. By leveraging findAll, find, collect, and mathematical aggregations directly within the assertion chain, you eliminate fragile indexing and write expressive, self-documenting tests for complex JSON responses.