Validating the Response Body

Response body validation is the process of verifying that the data returned by an API is correct, complete, and matches the expected values.

In REST Assured, response validation is performed using the then().body() method together with Hamcrest matchers such as:

  • equalTo()
  • notNullValue()
  • hasItem()
  • hasItems()
  • hasSize()
  • containsString()
  • greaterThan()
  • lessThan()

Interview Answer

"Response body validation ensures that the API returns the correct data. In REST Assured, I use then().body() along with Hamcrest matchers like equalTo(), notNullValue(), hasItem(), and hasSize() to validate key-value pairs, arrays, nested JSON objects, and dynamic values. If any expected value doesn't match the actual response, the test fails."

Advertisement

Response Validation Flow

 
API Request
      │
      ▼
Receive Response
      │
      ▼
Validate Status Code
      │
      ▼
Validate Response Body
      │
      ▼
Validate Headers
      │
      ▼
Validate Response Time
 

REST Assured Example

 
given()

.when()
        .get("/users/1")

.then()
        .statusCode(200)
        .body("id", equalTo(1))
        .body("name", notNullValue())
        .body("role", equalTo("Tester"));
 

What Can Be Validated?

You can validate:

  • Individual fields
  • Multiple fields
  • Arrays
  • Nested JSON
  • Dynamic values
  • Keys
  • Null values
  • Response size
  • Data types (using JsonPath or schema validation)

Common Hamcrest Matchers

Matcher Purpose
equalTo() Exact value comparison
notNullValue() Checks value exists
nullValue() Checks value is null
hasItem() Checks list contains a value
hasItems() Checks list contains multiple values
hasSize() Validates array size
containsString() Checks substring
greaterThan() Numeric comparison
lessThan() Numeric comparison

Real-Time Example

In my project, we validate static values, dynamic values, response keys, nested JSON objects, array sizes, and mandatory fields. If any validation fails, REST Assured automatically marks the test case as failed.


What is JSON?

JSON (JavaScript Object Notation) is a lightweight, text-based data format used to exchange information between a client and a server.

JSON is the most commonly used format in REST APIs because it is:

  • Lightweight
  • Human-readable
  • Easy to parse
  • Language-independent

Sample JSON

 
{
  "id": 101,
  "name": "John",
  "email": "john@test.com",
  "active": true
}
 

JSON Structure

A JSON document consists of:

  • Objects
  • Arrays
  • Keys
  • Values

Example

 
{
   Key : Value
}
 

JSON Data Types

Type Example
String "John"
Number 101
Boolean true
Object {}
Array []
Null null

Why JSON Is Preferred

  • Lightweight
  • Faster transmission
  • Easy parsing
  • Human-readable
  • Supported by almost every programming language

Interview Answer

"JSON stands for JavaScript Object Notation. It is a lightweight key-value-based data format used to exchange information between clients and servers. It is the most commonly used format for REST APIs because it is easy to read, parse, and process."


What is JsonPath?

JsonPath is an expression language used to navigate and retrieve values from a JSON document.

It is similar to XPath, but specifically designed for JSON.

JsonPath is commonly used for:


Sample JSON

 
{
   "user":{

      "id":101,

      "name":"John",

      "email":"john@test.com"

   }
}
 

JsonPath Expressions

Retrieve ID

 
user.id
 

Retrieve Name

 
user.name
 

Retrieve Email

 
user.email
 

REST Assured Example

 
String name =

response.jsonPath()
        .getString("user.name");
 

JsonPath Uses

  • Validate response values
  • Extract tokens
  • Extract IDs
  • Extract nested objects
  • API chaining

Interview Answer

"JsonPath is used to navigate JSON responses and extract specific values. It works like XPath for XML. In REST Assured, I use JsonPath to validate response values and extract dynamic data such as IDs, names, and authentication tokens for reuse in subsequent API requests."


JSON vs XML

Both JSON and XML are used for exchanging data between systems.

However, they differ in structure and usage.


JSON vs XML Comparison

Feature JSON XML
Format Key-Value Tag-Based
Size Lightweight More Verbose
Readability Easy More Complex
Parsing Faster Slower
Used In REST APIs SOAP Services
Validation JsonPath / JSON Schema XPath / XSD

JSON Example

 
{
   "name":"John"
}
 

XML Example

 
<User>
    <Name>John</Name>
</User>
 

When Is XML Used?

XML is commonly used in:

  • SOAP Web Services
  • Enterprise Systems
  • Legacy Applications

When Is JSON Used?

JSON is commonly used in:

  • REST APIs
  • Mobile Applications
  • Web Applications
  • Microservices
  • Cloud Services

Validating a Single Field

Single-field validation verifies one specific value in the response.


Example Response

 
{
   "status":"ACTIVE"
}
 

REST Assured Example

 
given()

.when()
        .get("/users/1")

.then()
        .statusCode(200)
        .body("status", equalTo("ACTIVE"));
 

Common Matchers

 
equalTo()

notNullValue()

containsString()

greaterThan()

lessThan()
 

Interview Answer

"Single-field validation checks one specific value in the response body. In REST Assured, I use then().body() together with Hamcrest matchers such as equalTo() or notNullValue()."


Validating Multiple Fields

Most API responses contain multiple fields.

REST Assured allows multiple validations by chaining several body() assertions.


Example Response

 
{
   "id":101,
   "name":"John",
   "role":"Tester"
}
 

REST Assured Example

 
given()

.when()
        .get("/users/101")

.then()
        .statusCode(200)
        .body("id", equalTo(101))
        .body("name", equalTo("John"))
        .body("role", equalTo("Tester"));
 

Benefits

  • Complete response validation
  • Better API verification
  • Reduced risk of missing issues
  • Cleaner test cases

Validating Arrays

Example Response

 
{
   "roles":[
      "Admin",
      "Tester",
      "Manager"
   ]
}
 

Check Array Contains Value

 
.body("roles",
      hasItem("Tester"))
 

Check Array Size

 
.body("roles",
      hasSize(3))
 

Validating Nested JSON

Response

 
{
   "user":{

      "id":101,

      "name":"John"

   }
}
 

Validation

 
.body("user.name",
      equalTo("John"))
 

Response Validation Flow

 
Status Code
      │
      ▼
Single Fields
      │
      ▼
Multiple Fields
      │
      ▼
Arrays
      │
      ▼
Nested Objects
 

Validating Response Time

Response time validation ensures that the API responds within an acceptable time limit.

This helps verify both functionality and performance.


REST Assured Example

 
given()

.when()
        .get("/users")

.then()
        .time(lessThan(2000L));
 

This verifies that the response is received within 2 seconds.


Validate Along with Status Code

 
given()

.when()
        .get("/users")

.then()
        .statusCode(200)
        .time(lessThan(3000L));
 

Why Validate Response Time?

Benefits include:

  • Performance verification
  • Early detection of slow APIs
  • SLA compliance
  • Better user experience

Real-Time Example

In our framework, every API test validates the status code, response body, and response time together. This ensures that the API is both functionally correct and performs within the expected response time.


Best Practices

  • Always validate the HTTP status code first.
  • Validate both static and dynamic response values.
  • Use JsonPath for nested objects and arrays.
  • Validate mandatory fields using notNullValue().
  • Validate array contents and sizes where applicable.
  • Include response time validation for critical APIs.
  • Combine response body validation with JSON Schema validation for complete contract verification.

Frequently Asked Questions (FAQs)

1. How do you validate the response body in REST Assured?

I use then().body() along with Hamcrest matchers such as equalTo(), notNullValue(), hasItem(), hasItems(), and hasSize() to validate individual fields, arrays, nested objects, and dynamic values returned by the API.


2. What is JSON?

JSON (JavaScript Object Notation) is a lightweight, key-value-based data format used for API request payloads and response bodies. It is human-readable, easy to parse, and is the preferred format for REST APIs.


3. What is JsonPath?

JsonPath is an expression language used to navigate JSON documents and extract or validate specific values. It is similar to XPath for XML and is widely used in REST Assured for response validation and API chaining.


4. What is the difference between JSON and XML?

JSON is lightweight, key-value based, easy to read, and commonly used in REST APIs. XML is tag-based, more verbose, and is commonly used in SOAP web services. REST Assured supports both formats.


5. How do you validate a single field?

Use then().body() with a JsonPath expression and a Hamcrest matcher.

Example:

 
.body("status", equalTo("ACTIVE"))
 

6. How do you validate multiple fields?

Chain multiple body() assertions together with the status code validation.

Example:

 
.body("id", equalTo(101))
.body("name", equalTo("John"))
.body("role", equalTo("Tester"))
 

This verifies several response fields in a single test.


7. How do you validate response time?

REST Assured provides the time() assertion to verify that the API responds within an acceptable threshold.

Example:

 
.time(lessThan(2000L))
 

This ensures that the API meets the expected performance requirements while also validating its functional behavior.