REST Assured Logging & Response Extraction
When an API test fails in CI, the first question is always "what exactly did we send, and what came back?". REST Assured's logging answers that; its extraction methods pull values out of responses for assertions and for the next request in a chain. This guide covers both — including the framework-level setup most tutorials skip: logging only on failure, logging to a file, and hiding secrets.
Part 1 — Logging
Logging methods
| Method | Logs | Where |
|---|---|---|
.log().all() |
Everything — method/URI or status, headers, cookies, body | Request or response |
.log().body() |
Body only | Request or response |
.log().headers() |
Headers only | Request or response |
.log().cookies() |
Cookies | Request or response |
.log().params() |
Query, form and path parameters | Request |
.log().method() / .log().uri() |
HTTP method / full URI | Request |
.log().status() |
Status line | Response |
.log().ifError() |
Everything, only for 4xx/5xx responses | Response |
.log().ifValidationFails() |
Everything, only when an assertion fails ⭐ | Request or response |
Request logging goes after given(); response logging goes after then():
given()
.log().all() // what we send
.contentType(ContentType.JSON)
.body(newUser)
.when()
.post("/users")
.then()
.log().all() // what came back
.statusCode(201);
Log only when something fails ⭐
given()
.log().ifValidationFails() // request, printed only if the test fails
.when()
.get("/users/101")
.then()
.log().ifValidationFails() // response, printed only if the test fails
.statusCode(200)
.body("name", equalTo("John"));
Passing tests stay quiet; a failing test prints the full request and response next to the assertion error — exactly what you need in CI logs.
Turn it on once for the whole framework
@BeforeSuite
public void setUpRestAssured() {
RestAssured.baseURI = ConfigReader.get("apiBaseUrl");
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
}
Hide tokens and passwords in logs
Logs end up in CI consoles and reports, so never print real credentials. Blacklisted headers are shown as [ BLACKLISTED ]:
RestAssured.config = RestAssured.config()
.logConfig(LogConfig.logConfig().blacklistHeader("Authorization", "Cookie", "x-api-key"));
Also avoid logging request bodies that contain passwords (login calls) — log the status and a summary instead.
Write logs to a file (or a report)
PrintStream apiLog = new PrintStream(new FileOutputStream("target/api.log", true), true);
RestAssured.filters(
new RequestLoggingFilter(apiLog),
new ResponseLoggingFilter(apiLog));
Filters apply to every request. Many frameworks write a custom filter that attaches the request and response to the Extent or Allure report instead — so each test's report entry shows its own API traffic.
Real-time example
A test started returning 401 only in CI. The failure log showed the request had no Authorization header: the token variable was read from an environment variable that wasn't set on the CI agent. Without request logging, the 401 looked like an API bug.
Part 2 — Extracting Values
Sample response from GET /users/101:
{
"id": 101,
"name": "John",
"token": "abc123xyz",
"user": { "city": "Hyderabad" },
"orders": [
{ "id": 1, "item": "Laptop", "amount": 55000 },
{ "id": 2, "item": "Mouse", "amount": 800 }
]
}
The whole response
Response response = given().when().get("/users/101").then().statusCode(200).extract().response();
String body = response.asString(); // or response.getBody().asString()
int status = response.getStatusCode();
String type = response.getContentType();
String requestId = response.getHeader("X-Request-Id");
long timeMs = response.getTime();
One value, directly (typical for chaining)
String token = given().body(credentials)
.when().post("/login")
.then().statusCode(200)
.extract().path("token");
int userId = response.path("id");
JsonPath
JsonPath navigates JSON the way XPath navigates HTML. REST Assured uses GPath syntax: dots for nesting, [index] for arrays.
JsonPath json = response.jsonPath();
json.getString("name"); // "John"
json.getInt("id"); // 101
json.getString("user.city"); // "Hyderabad" — nested
json.getString("orders[0].item"); // "Laptop" — array index
json.getList("orders.item"); // ["Laptop", "Mouse"] — one field from every element
json.getInt("orders.size()"); // 2
json.getString("orders.find { it.id == 2 }.item"); // "Mouse" — search by value
json.getList("orders.findAll { it.amount > 1000 }.item"); // ["Laptop"]
json.getMap("orders[0]"); // the first order as a Map
json.getList("orders", Order.class); // the orders as POJOs
| Method | Returns |
|---|---|
getString(), getInt(), getLong(), getDouble(), getBoolean() |
A typed single value |
getList(path) / getList(path, Type.class) |
A list — of raw values or mapped objects |
getMap(path) |
An object as a Map |
getObject(path, Type.class) |
A nested object mapped to a POJO |
get(path) |
Whatever type the value is |
For whole responses, deserializing to a POJO is often cleaner than many JsonPath calls — see POJO & Serialization.
Common JsonPath errors
nullinstead of a value — a typo in the path or a different nesting level; log the body and check the structure.- ClassCastException — the wrong getter, e.g.
getInt()on a value that's a string or a large number (usegetLong()). - Index out of range / null for
orders[5]— the array is shorter than expected; assert its size first. - Brittle index paths — prefer
find { … }over positions when order can change. - Special characters in keys (such as
first-name) — quote them:"'first-name'".
Extract or assert?
If you only need to check a value, assert inside then() (.body("name", equalTo("John"))) — the failure message is clearer. Extract when the value feeds the next request (tokens, IDs) or needs logic that matchers can't express. More: Response Validation in REST Assured.
See the request–response cycle, logging and extraction step by step in the REST Assured Visualizer.
From Real Projects
My API experience covers CRUD operations, HTTP methods, JSON path, and validating JSON and XML responses, and my automation work was in Java with TestNG. That combination is exactly what REST Assured builds on: HTTP calls in Java, JSON path for extracting values, and TestNG for running and grouping the tests. If you already know Selenium with TestNG, REST Assured fits into the same project structure. Testsigma supports web, mobile and API test automation, so understanding APIs was part of understanding the product I was testing. Log full requests and responses only when a test fails, to keep reports readable.
📚 Official documentation: REST Assured official site · MDN: HTTP
FAQs
How do you log requests and responses in REST Assured?
Add .log().all() (or body(), headers(), params()…) after given() for the request and after then() for the response.
What is the best logging approach for a framework?
log().ifValidationFails() — or RestAssured.enableLoggingOfRequestAndResponseIfValidationFails() globally — with sensitive headers blacklisted.
How do you hide the Authorization header in logs?
Configure LogConfig.logConfig().blacklistHeader("Authorization"); the value is replaced with a placeholder.
How do you extract the response body as a string?
response.asString(), or .then().extract().response().asString() in one chain.
How do you extract a value for the next request?
.then().extract().path("token") or response.jsonPath().getString("token").
How do you get one field from every item in an array?
jsonPath().getList("orders.item") — GPath collects the field from each element.
Related
- The Complete REST Assured Tutorial
- REST Assured Authentication
- REST Assured Framework Design
- REST Assured Cheat Sheet