Q12 of 40 · REST Assured

Explain JsonPath in REST Assured with a nested-object example.

REST AssuredMidrest-assuredjsonpathgpathassertionsapi-testing

Short answer

Short answer: REST Assured's JsonPath uses dot notation for nested objects, bracket notation for arrays, and Groovy GPath for collection operations. Paths like "order.shipping.city" navigate nesting; "items[0].price" accesses array elements; "items.findAll{it.active}.name" filters with a predicate.

Detail

REST Assured embeds a JsonPath implementation based on Groovy's GPath. The path language is more expressive than simple dot-notation JSON pointers:

Basic navigation:

  • "user.address.city" — nested field
  • "items[0].sku" — first element of an array
  • "items[-1].sku" — last element
  • "items.size()" — array length

Collection operations (Groovy GPath):

  • "items.price" — list of all prices across the items array
  • "items.findAll{it.active}.name" — names of all active items
  • "items.find{it.id == 3}.name" — name of the item with id=3
  • "items.collect{it.price}.sum()" — sum of all prices

Standalone use: you can also pull the whole path object for multi-step inspection:

JsonPath jp = response.jsonPath();
String city = jp.getString("order.shipping.city");
List<String> names = jp.getList("items.name", String.class);

// EXAMPLE

// Response body:
// { "order": { "id": 5, "items": [
//     { "sku": "A1", "price": 10.0, "active": true },
//     { "sku": "B2", "price": 20.0, "active": false }
//   ], "shipping": { "city": "London" } } }

given(reqSpec)
.when()
    .get("/orders/5")
.then()
    .statusCode(200)
    // nested field
    .body("order.shipping.city",     equalTo("London"))
    // first array element
    .body("order.items[0].sku",      equalTo("A1"))
    // array size
    .body("order.items.size()",      equalTo(2))
    // GPath filter — names of active items only
    .body("order.items.findAll{it.active}.sku", hasItem("A1"))
    // sum of all prices
    .body("order.items.collect{it.price}.sum()", equalTo(30.0f));

// WHAT INTERVIEWERS LOOK FOR

Dot notation for nesting, bracket notation for arrays, and at least one Groovy GPath expression (findAll, collect, size). Candidates who can write findAll predicates have clearly used REST Assured in production rather than only in tutorials.

// COMMON PITFALL

Extracting the full response as a Map and then navigating manually with Java — this works but discards the concise JsonPath expressions. The power of REST Assured's body() is the path expression, not the matcher.