← Back to libraryQuestion 233 of 468
🔌REST AssuredIntermediate

Body Validation with JsonPath / GPath

📌 Definition:

REST Assured validates JSON response bodies using a GPath expression in .body(path, matcher). Paths navigate the JSON (dot notation, array indexes, filters) and Hamcrest matchers assert on the extracted value.

📖 Detailed Explanation:

body('user.name', equalTo('QA')) checks a nested field; body('data[0].id', equalTo(1)) indexes an array; body('items.size()', equalTo(3)) counts; body('users.name', hasItems('A', 'B')) checks a collection of a field across all elements; body('users.find { it.id == 5 }.name', equalTo('X')) uses a GPath filter (Groovy). You can chain multiple .body() assertions. GPath differs slightly from JsonPath but is powerful for filtering/aggregating. Getting the path right (especially root arrays vs objects, and collection projections) is the core skill of REST Assured body validation.

🔑 Key Points:
  • body(gpath, matcher) validates JSON fields
  • Index arrays [0], count with .size(), project collections
  • GPath filters: find { it.id == 5 }.name
  • Chain multiple .body() assertions
🌍 Real-World Example:

Verifying a list endpoint: then().body('size()', equalTo(10)).body('id', hasItems(1, 2, 3)).body('find { it.name == "QA" }.active', equalTo(true)) — counting, checking membership, and filtering in one chain.

🎯 Scenario-Based Interview Question:

The API returns a JSON ARRAY at the root: [{"id":1},{"id":2}]. How do you assert the first element's id is 1?