Logging Requests and Responses
Logging is the process of printing request and response details during API execution.
It helps testers understand exactly:
- What was sent to the server
- What the server returned
- Why a test passed or failed
REST Assured provides built-in logging methods that make debugging API failures much easier.
Interview Answer
"Logging in REST Assured helps us understand exactly what is sent in the request and what is received in the response. I commonly use
.log().all()while developing test cases and.log().ifValidationFails()in CI/CD pipelines to keep execution logs clean while still capturing complete details when a test fails."
Why Logging Is Important
Logging helps identify issues such as:
- Incorrect payloads
- Missing request headers
- Invalid authentication tokens
- Wrong query parameters
- Incorrect path parameters
- Unexpected status codes
- Incorrect response body
- API contract violations
Without logging, debugging API failures becomes much more difficult.
Request–Response Logging Flow
Request
│
▼
REST Assured
│
▼
Logs Request Details
│
▼
API Execution
│
▼
Logs Response Details
│
▼
Validation
Logging Methods in REST Assured
REST Assured provides several built-in logging methods.
| Method | Description |
|---|---|
.log().all() |
Logs everything |
.log().body() |
Logs only the request/response body |
.log().headers() |
Logs only the headers |
.log().cookies() |
Logs cookies |
.log().params() |
Logs parameters |
.log().ifValidationFails() |
Logs only when validation fails |
Log Complete Request
given()
.log().all()
.when()
.get("/users");
This logs:
- URL
- Headers
- Parameters
- Cookies
- Request Body
Log Complete Response
response.then()
.log().all();
This logs:
- Status Code
- Headers
- Response Body
- Response Time
Log Only Request/Response Body
given()
.log().body()
.when()
.post("/users");
or
response.then()
.log().body();
Useful when you only want to inspect the JSON or XML payload.
Log Only Headers
given()
.log().headers()
.when()
.get("/users");
or
response.then()
.log().headers();
Useful for verifying:
- Content-Type
- Authorization
- Cache-Control
- Server
- Cookies
Logging Only When Validation Fails (Best Practice)
A common best practice is to log details only when a validation fails.
This keeps execution logs clean while still providing complete debugging information when required.
Example:
given()
.when()
.get("/users")
.then()
.log().ifValidationFails()
.statusCode(200);
Logging Comparison
| Method | Logs | Best Used For |
|---|---|---|
.log().all() |
Request/Response completely | Debugging while developing |
.log().body() |
Only body | Payload validation |
.log().headers() |
Only headers | Header validation |
.log().ifValidationFails() |
Only failed executions | CI/CD pipelines |
Real-Time Example
During one API failure, the request logs clearly showed that the
Authorizationheader was missing. After adding the missing bearer token, the API returned 200 OK instead of 401 Unauthorized.
Best Practices for Logging
- Use
.log().all()during development. - Use
.log().ifValidationFails()in automated CI/CD executions. - Avoid logging sensitive information such as passwords or tokens in production logs.
- Log request and response details for failed test cases.
- Capture response time along with request and response details.
Extracting the Response Body as a String
Sometimes the complete response needs to be stored for:
- Custom validation
- Logging
- Parsing
- Data extraction
- Dynamic API chaining
REST Assured allows the entire response body to be extracted as a string.
Method 1
String responseBody =
response.getBody().asString();
Method 2
String responseBody =
given()
.when()
.get("/users")
.then()
.extract()
.response()
.asString();
Response Extraction Flow
API Request
│
▼
Receive Response
│
▼
Extract Response Body
│
▼
Store as String
│
▼
Parse / Validate / Log
Why Extract the Response as a String?
Useful when:
- Response structure is dynamic.
- Custom parsing is required.
- Response needs to be logged.
- Data needs to be stored.
- Third-party libraries process the response.
Real-Time Example
We extract the complete response body as a string whenever we need to manually parse a dynamic response or log the entire response for debugging. It is also useful before extracting specific values using JsonPath.
Extracting Values Using JsonPath
JsonPath is used to navigate a JSON response and extract specific values.
It is similar to XPath, but designed for JSON.
JsonPath is widely used in REST Assured for:
- Response validation
- Dynamic token extraction
- API chaining
- Data verification
Sample JSON Response
{
"id": 101,
"name": "John",
"email": "john@test.com",
"token": "abc123xyz"
}
Extract a String Value
String token =
response.jsonPath()
.getString("token");
Extract an Integer
int id =
response.jsonPath()
.getInt("id");
Extract Using extract()
String token =
given()
.when()
.post("/login")
.then()
.extract()
.jsonPath()
.getString("token");
Extract Nested Values
Suppose the response is:
{
"user":{
"id":101,
"name":"John"
}
}
Extract the name:
String name =
response.jsonPath()
.getString("user.name");
Extract Array Values
Suppose:
{
"users":[
{
"id":101
},
{
"id":102
}
]
}
Extract the first user ID:
int id =
response.jsonPath()
.getInt("users[0].id");
JsonPath Flow
JSON Response
│
▼
JsonPath Expression
│
▼
Extract Value
│
▼
Validation / API Chaining
Common JsonPath Methods
| Method | Description |
|---|---|
getString() |
Returns String value |
getInt() |
Returns Integer |
getBoolean() |
Returns Boolean |
getFloat() |
Returns Float |
getDouble() |
Returns Double |
getList() |
Returns List |
getMap() |
Returns Map |
Common JsonPath Errors
Issues commonly occur when:
- The response is not valid JSON.
- The JsonPath expression is incorrect.
- The key does not exist.
- The extracted value is
null. - The expected data type does not match the actual value.
Always verify the response structure before writing JsonPath expressions.
Real-Time Example
After executing the Login API, I extracted the JWT token using
response.jsonPath().getString("token"). I reused this token in theAuthorizationheader while calling the Product and Order APIs, enabling complete end-to-end API automation.
Best Practices
- Use
.log().ifValidationFails()for CI/CD execution. - Use
.log().all()while developing and debugging. - Extract dynamic values using JsonPath instead of hardcoding them.
- Validate extracted values before using them in subsequent requests.
- Keep JsonPath expressions simple and readable.
- Store commonly used JsonPath expressions in reusable utility methods where appropriate.
Frequently Asked Questions (FAQs)
1. How do you log requests and responses in REST Assured?
REST Assured provides several logging methods:
.log().all()– Logs the complete request or response..log().body()– Logs only the body..log().headers()– Logs only the headers..log().cookies()– Logs cookies..log().ifValidationFails()– Logs details only when a validation fails.
2. What is the best-practice logging method?
The recommended approach for automation frameworks is .log().ifValidationFails() because it keeps execution logs clean while still capturing complete request and response details whenever a test fails.
3. Why is logging important?
Logging helps identify issues such as incorrect payloads, missing headers, invalid authentication, unexpected status codes, incorrect response bodies, and API contract violations. It significantly reduces debugging time by showing exactly what was sent and received.
4. How do you extract the response body as a string?
You can extract the response body using either:
response.getBody().asString();
or
.extract().response().asString();
This is useful for manual parsing, logging, or handling dynamic response structures.
5. What is JsonPath used for?
JsonPath is used to navigate JSON responses and extract specific values such as IDs, names, tokens, nested objects, or array elements. These extracted values are commonly used for response validation and API chaining.
6. How do you extract a value using JsonPath in REST Assured?
You can extract values using methods such as:
response.jsonPath().getString("token");
or
.extract().jsonPath().get("id");
These methods are commonly used to retrieve dynamic values like authentication tokens, user IDs, product IDs, or order IDs for use in subsequent API requests.