Validating Response Codes & Body
Learning Outcome
3
2
1
Understand the importance of API response validation
Verify HTTP status codes using Rest Assured
Validate response body using string matching and JSON Path
Apply assertions to ensure correct API behavior
4
Without validation, tests are meaningless. Validation ensures correctness, reliability, and confidence in APIs.
When an API request is executed, receiving a response from the server is not enough.
Testers must verify whether the response is correct, complete, and meets the expected requirements.
Response validation ensures that the API behaves as expected and returns accurate data to the client application.
It helps detect issues such as incorrect status codes, missing fields, invalid data formats, or unexpected responses.
What Can Be Validated in Rest Assured
Rest Assured allows testers to validate different parts of the API response, such as:
Response Body – Verifies that the returned data contains expected values
Headers – Checks metadata information like authentication tokens or server details.
Content Type – Confirms the response format (e.g., JSON, XML).
Status code – Ensures the API request was processed successfully (e.g., 200, 201).
What to validate ?
Status Code
Indicates the result of an API request
Confirms whether request was successful or failed
This is the first level of validation
Quickly tells if request succeeded or failed
Status code alone is not enough
Examples :
200 → Success
201 → Created
400 → Bad Request
404 → Not Found
500 → Server Error
Status Code
Status Code
Contains actual data returned by the API
Used to verify business logic and correctness
Can validate:
Specific fields (e.g., name, id)
Values and formats
Nested JSON structures
This is the most critical part, Even if status is 200, data can be wrong
Always validate important fields and values
Headers
Provide metadata about the response
Used for validation of:
Authorization details
Caching information
Server and response behavior
These carry additional information
Useful in advanced scenarios like auth, caching
Content Type
Defines the format of the response
Ensures API returns expected data type
Common types:
application/json
application/xml
text/html
Prevents issues when parsing response
Response Time
Measures how fast the API responds
Important for performance testing
Helps ensure API meets SLA requirements
Slow APIs can still be “correct” but not usable
Response Time
Think of API validation like ordering food —
Status code tells you the order arrived,
But response body tells you if it’s the correct dish.”
Asserting HTTP status code
Validating simple JSON Response
Validation using jsonPath()
JSON Path is a syntax used to navigate and extract data from a JSON response
It helps access specific fields, values, and nested elements easily
Accessing Values Using JSON Pathg
data.id → 101
data.user.name → John
data.user.age → 30
JSON Path is like addressing system for JSON data
Very useful when working with complex API responses
It allows us to go directly to the required field
(Public API)
How JSON Path is Used in Validation
Used inside .body() method to validate response fields
Helps verify specific values in API response
Example :
.then().body("data.user.name", equalTo("John"));
What happens here ??
Navigates to → data.user.name
Extracts value → "John"
Compares with expected value using equalTo()
1 . Validate List Value
.then().body("users[0].name", equalTo("John"));
2 . Validate Multiple Values
.then()
.body("data.id", equalTo(101))
.body("data.user.age", equalTo(30));
Handles nested JSON easily
Why JSON Path is important
Makes validation clean and readable
Reduces complexity in API tests
Using jsonPath() for Nested Values
Response response = given()
.baseUrl("https://api.example.com")
.when()
.get("/user/details");
String city = response.jsonPath().getString("address.city");
System.out.println("City: " + city);
JSON Path is like Google Maps for your API response —
it takes you exactly where your data is.”
What is Extracting Response Data ??
Process of retrieving specific values from API response
Stored in variables for reuse in test automation
Enables dynamic and real-time testing
Why is it important ??
APIs often return dynamic data (IDs, tokens, etc.)
Hardcoding values is not reliable
Helps in:
getString("name")
String name = response.jsonPath().getString("name");
Extracts value of the given field as String
Automatically reads from JSON response
Response
Represents the API response object
Contains full response (body, headers, status, etc.)
API returns JSON response
jsonPath() helps navigate it
"name" field is extracted
Value stored in variable → name
Step 1 : Get User
Response response = given()
.when()
.get("/users/1");Step 2 : Extract ID
int id = response.jsonPath().getInt("id");given()
.pathParam("id", id)
.when()
.get("/orders/{id}")
.then()
.statusCode(200);Step 3 : Use in Next API
Supports API chaining
Makes tests dynamic (no hardcoding)
Improves real-world test coverage
Other extraction methods:
getBoolean() → for true/false
getList() → for arrays
getInt() → for integers
Validating Response Headers
You can even Print your response data and also use it for
API correctness is important, but speed is equally important
Even if API returns correct data, if it takes too long → bad user experience
Payment API taking 10 seconds → unacceptable
.time(lessThan(2000L)) means response should come within 2 seconds
Response time validation is part of basic performance testing
Explain real-world usage:
Load testing
Performance benchmarking
SLA validation
What is Response Time Validation?
Process of measuring how long an API takes to respond
Ensures API performance is within acceptable limits
“A fast wrong response is bad… but a slow correct response is also a problem.”
Why is it Important
Slow APIs impact user experience
Helps identify performance bottlenecks
Ensures API meets SLA (Service Level Agreement)
Critical for high-traffic applications
.then().time(lessThan(2000L));
time()
Used to capture and validate API response time
Works with matchers to define acceptable limits
lessThan()
Matcher used to check if response time is below a specified value
Example
lessThan(2000L) → Response should be under 2000 ms
long time = response.getTime();
getTime()
Works with matchers to define acceptable limits
Extracts actual response time
System.out.println("Response Time: " + time);
1. API request is sent
2. Response time is measured (in milliseconds)
3.Compared with expected threshold
4.Test passes if response is within limit
Best Practices
Set realistic time limits based on system performance.
Avoid strict thresholds in unstable environments.
Combine performance checks with functional validation.
Monitor trends instead of single executions
Always validate status codes and critical fields
Create reusable validation methods.
Handle both success and failure cases.
Keep validations clean and modular.
Use JSON path for precise validation.
Common Mistakes to Avoid
Summary
4
Proper assertions improve test quality
3
Rest Assured makes validation simple using BDD
2
Status code + body validation ensures accuracy
1
Response validation is key in API testing
Quiz
What does Content Type in an API response indicate?
A. API performance
B. Format of the response data
C. Status of the request
D. Authentication method
Quiz-Answer
What does Content Type in an API response indicate?
A. API performance
C. Status of the request
D. Authentication method
B. Format of the response data