When working with APIs, validating the JSON response is a critical aspect of ensuring the API behaves as expected. Rest Assured, a powerful library for API testing in Java, provides seamless ways to validate JSON responses with its intuitive methods.
In this blog post, we'll explore step-by-step how to validate the JSON body of a response using Rest Assured.
What is JSON Body Validation?
When an API call is made, it typically returns a response in JSON format. JSON body validation involves verifying the following aspects:
- Structure: Checking if the keys and nested objects exist.
- Values: Ensuring values match the expected ones.
- Data Types: Confirming the types of values (string, number, array, etc.).
Setting Up Rest Assured
Before jumping into JSON validation, ensure your project is ready with the necessary dependencies.
1. Maven Dependency
Add the following dependency in your pom.xml
:
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.3.0</version> <!-- Use the latest version -->
</dependency>
2. Sample JSON Response
For this example, let’s assume the API returns the following JSON:
{
"id": 1,
"name": "Pavan Kumar",
"role": "SDET-QA",
"skills": ["Java", "Selenium", "Rest Assured"],
"isActive": true
}
Validating JSON Body in Rest Assured
1. Basic JSON Validation
To validate simple key-value pairs:
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class ValidateJSON {
public static void main(String[] args) {
given()
.baseUri("https://api.example.com")
.when()
.get("/user/1")
.then()
.statusCode(200) // Validate status code
.body("name", equalTo("Pavan Kumar")) // Check specific value
.body("role", equalTo("SDET-QA")); // Validate role
}
}
Here:
body("key", Matcher)
is used to assert JSON fields.equalTo()
checks for equality.
2. Validate Nested JSON
If the JSON response contains nested objects or arrays:
{
"id": 1,
"name": "Pavan Kumar",
"address": {
"city": "Hyderabad",
"zip": "500081"
}
}
3. Validate JSON Arrays
For arrays, you can verify elements individually or check the entire array:
given()
.baseUri("https://api.example.com")
.when()
.get("/user/1")
.then()
.statusCode(200)
.body("skills", hasSize(3)) // Check array size
.body("skills", hasItem("Java")) // Check if array contains an item
.body("skills", contains("Java", "Selenium", "Rest Assured")); // Match exact order
4. Validate Using Logical Matchers
You can use logical conditions for more flexible validation:
given()
.baseUri("https://api.example.com")
.when()
.get("/user/1")
.then()
.statusCode(200)
.body("isActive", is(true)) // Validate boolean
.body("id", greaterThan(0)) // Validate numerical condition
.body("name", notNullValue()); // Ensure value is not null
5. Extract and Validate Response
Sometimes, you might need to extract values for further validation:
import io.restassured.response.Response;
Response response =
given()
.baseUri("https://api.example.com")
.when()
.get("/user/1");
String name = response.jsonPath().getString("name");
int id = response.jsonPath().getInt("id");
System.out.println("Name: " + name);
System.out.println("ID: " + id);
// Custom Assertions
assert name.equals("Pavan Kumar");
assert id == 1;
Best Practices
- Use Hamcrest Matchers: Simplifies assertions with readable methods like
equalTo
,hasSize
, etc. - Break Down Validations: Avoid writing long validation chains in a single
.then()
block. - Log Responses: Use
.log().all()
for debugging failed tests. - Reusable Methods: For large projects, create reusable methods to handle JSON validation.