Post

Log REST Assured Requests and Responses

Use REST Assured's log() to print requests and responses: everything, single parts, only when validation fails, only for errors, or only for one status code.

Log REST Assured Requests and Responses

An account test fails on the build server with Expected status code <200> but was <404>, and passes on your laptop. Did the request go to the right URL? Was the query parameter sent? What did the server say in the body? In this guide, you’ll make REST Assured print the exact request and response, so questions like these answer themselves.

Level: Beginner · Time: 15 minutes · Part of: Module 1: Foundations, section 5

What You’ll Build

You’ll build a test class called LoggingTest with five tests. Each one uses a different logging option, so you can compare what each prints next to the code that printed it.

The first test sends this request, and logs it and its response in full:

1
2
3
4
5
6
7
GET /api/v1/accounts/acc-1001 HTTP/1.1
Host: localhost:<port>

HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8

{"id":"acc-1001","owner":"Anna de Vries", ...}

When you’re done, Maven reports five passing tests, with the logged requests and responses printed above the result:

1
2
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

In this guide, you will:

  • Log the whole request and response.
  • Log only the parts you need.
  • Log only when a check fails.
  • Log only for certain status codes.

What You Need

How to Complete This Guide

You can work through this guide in one of two ways:

  • Build it step by step: create LoggingTest in a new section_05 package next to the classes from the previous sections, and follow every heading below.
  • Skip ahead: open the finished class (LoggingTest.java) and read along. You can run it at any time with the command in Run the Tests.

Get the code: if you haven’t cloned the examples repository yet, follow the steps in Send Your First REST Assured Request.

Out of scope: this guide doesn’t cover hiding secrets such as Authorization headers in logs, or writing your own logging filters; they’re taught in Module 5 and Module 8.

Understand Request and Response Logging

The problem. A failure message tells you what a check expected and what it got, but not why. A 404 might come from a missing base path, a misspelled id or a query parameter that was never sent. Without the request and response in front of you, you guess.

The concept. log() returns a logging specification that prints to standard out. Where you call it decides what it logs:

  • Before when(), it logs the request, as REST Assured is about to send it.
  • After then(), it logs the response, as it came back.

The options fall into three groups: everything with all(), single parts such as uri() or body(), and conditional options such as ifValidationFails() that print only when something specific happens. Surefire shows standard out in the console and the test report, and your IDE shows it in the test runner, so there’s nothing to configure.

When to use each. Log everything while you explore a new endpoint. Log single parts when you need one fact, such as the final URL. In the suites you keep, log only on failure: a green build stays quiet, and a red one prints what you need to debug it.

Log on failure by default, and log everything only while you explore.

Meet the API Under Test

This guide uses the account endpoints of the Accounts API, under the base path /api/v1:

MethodPathPurpose
GET/accountsList all accounts, optionally filtered
GET/accounts/{id}Fetch one account

For acc-1001, the account endpoint returns a response similar to the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
X-request-id: bd946bcc-2d15-41bb-a3c9-bef040ebc67f
Cache-control: no-store

{
    "id": "acc-1001",
    "iban": "NL91ABNA0417164300",
    "owner": "Anna de Vries",
    "type": "CURRENT",
    "currency": "EUR",
    "balance": 1250.50,
    "status": "ACTIVE",
    "openedOn": "2019-04-01"
}

An unknown account such as acc-9999 returns a 404 with a problem details body whose title is "Not Found".

Your tests check two things:

  • The id field of acc-1001, which the failure-only logging test reads.
  • The status codes 200 and 404, which decide whether the conditional options print.

Log the Whole Request and Response

Set Up the Test Class

Goal: create the test class, start the API and add the shared request helper.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.javanibble.module_01.section_05;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

import com.javanibble.accounts.AccountsApi;

import io.restassured.filter.log.LogDetail;
import io.restassured.specification.RequestSpecification;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

class LoggingTest {

    private static AccountsApi api;

    @BeforeAll
    static void startApi() {
        api = AccountsApi.start();
    }

    @AfterAll
    static void stopApi() {
        api.close();
    }

    private static RequestSpecification accountsApi() {
        return given()
            .baseUri(api.baseUri())
            .port(api.port())
            .basePath(AccountsApi.BASE_PATH);
    }
}

What’s happening:

  • The lifecycle methods and the accountsApi() helper are the same as in the previous section.
  • LogDetail is new. You’ll use it to choose how much to print when a check fails.

Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.

Log Everything

Goal: print the whole request before it’s sent and the whole response after it arrives.

1
2
3
4
5
6
7
8
9
10
@Test
void logTheWholeRequestAndResponse() {
    accountsApi()
        .log().all()
    .when()
        .get("/accounts/{id}", "acc-1001")
    .then()
        .log().all()
        .statusCode(200);
}

What’s happening:

  • log().all() before when() prints the method, URI, parameters, headers, cookies and body of the request.
  • log().all() after then() prints the status line, headers, cookies and body of the response.

Checkpoint: run LoggingTest from your IDE. The test passes, and the output starts with the request:

1
2
3
4
5
6
7
8
9
10
11
Request method:	GET
Request URI:	http://localhost:56123/api/v1/accounts/acc-1001
Proxy:			<none>
Request params:	<none>
Query params:	<none>
Form params:	<none>
Path params:	<none>
Headers:		Accept=*/*
Cookies:		<none>
Multiparts:		<none>
Body:			<none>

The response follows, with its status line, headers and a pretty-printed body, the same as in Meet the API Under Test. The port, date and request id change on every run.

The Request URI line is the final URL, built from baseUri, port, basePath and the path. It’s the quickest way to check the URL-building rules from Control Where REST Assured Requests Go.

A request log prints every header and cookie, including Authorization tokens and session ids. Build output is often kept for a long time and shared widely, so don’t leave log().all() on requests that carry credentials.

Log Only the Parts You Need

Printing everything for every request makes a large suite unreadable. You can pick single parts instead.

Pick Single Parts

Goal: print only the method and URL of the request, and the status, headers and body of the response.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void logOnlyParts() {
    accountsApi()
        .queryParam("status", "ACTIVE")
        .log().method()
        .log().uri()
    .when()
        .get("/accounts")
    .then()
        .log().status()
        .log().headers()
        .log().body()
        .statusCode(200);
}

What’s happening:

  • log().method() and log().uri() print two lines of the request. The URI includes the query string, so you can see the parameter was sent.
  • log().status(), log().headers() and log().body() print three parts of the response. JSON bodies are pretty-printed.
  • The request parts are all(), method(), uri(), params(), headers(), cookies() and body(). The response parts are all(), status(), headers(), cookies() and body().

Checkpoint: run the class again. Both tests pass, and this test prints a much shorter log, starting with:

1
2
3
Request method:	GET
Request URI:	http://localhost:56123/api/v1/accounts?status=ACTIVE
HTTP/1.1 200 OK

The headers and the body of the three active accounts follow.

Body logs are pretty-printed, so the whitespace you see may differ from what was sent on the wire. Don’t use a log to debug formatting differences in the raw body.

Log Only When a Check Fails

This is the option most real suites use. Nothing is printed while the test passes.

Log on Validation Failure

Goal: print the request and the response only if a check after then() fails.

1
2
3
4
5
6
7
8
9
10
@Test
void logOnlyWhenSomethingFails() {
    accountsApi()
        .log().ifValidationFails()
    .when()
        .get("/accounts/{id}", "acc-1001")
    .then()
        .log().ifValidationFails(LogDetail.ALL)
        .body("id", equalTo("acc-1001"));
}

What’s happening:

  • log().ifValidationFails() before when() holds the request log back, and prints it only if the test fails.
  • log().ifValidationFails(LogDetail.ALL) after then() does the same for the response.
  • LogDetail chooses how much to print. LogDetail.ALL is the default, and values such as LogDetail.URI, LogDetail.HEADERS or LogDetail.BODY narrow it down.

Checkpoint: run the class again. Three tests pass, and this one prints nothing, because every check holds. You’ll make it print in Make a Test Fail.

Put log() before the checks. After then(), each check runs straight away, so a log().all() placed after a failing check is never reached and prints nothing. ifValidationFails() placed first doesn’t have this problem.

Log Only for Certain Status Codes

Log Error Responses

Goal: print the response only when its status code is 400 or higher.

1
2
3
4
5
6
7
8
9
@Test
void logTheResponseOnlyForErrorStatusCodes() {
    accountsApi()
    .when()
        .get("/accounts/{id}", "acc-9999")
    .then()
        .log().ifError()
        .statusCode(404);
}

What’s happening:

  • log().ifError() prints the response if its status code is 400 or higher, whether or not the test passes.
  • acc-9999 doesn’t exist, so the API answers 404 and the response is printed.

Checkpoint: run the class again. Four tests pass, and this one prints the 404 response:

1
2
3
4
5
6
7
8
9
10
11
HTTP/1.1 404 Not Found
Content-type: application/problem+json; charset=utf-8
...

{
    "type": "about:blank",
    "title": "Not Found",
    "status": 404,
    "detail": "Account acc-9999 does not exist",
    "instance": "/api/v1/accounts/acc-9999"
}

Log One Status Code

Goal: print the response only for a status code you never expect, such as a 500.

1
2
3
4
5
6
7
8
9
@Test
void logTheResponseOnlyForOneStatusCode() {
    accountsApi()
    .when()
        .get("/accounts")
    .then()
        .log().ifStatusCodeIsEqualTo(500)
        .statusCode(200);
}

What’s happening:

  • log().ifStatusCodeIsEqualTo(500) prints the response only if the status code is exactly 500.
  • The list endpoint answers 200, so nothing is printed. If the server ever fails, the log shows the error body next to the failed statusCode(200) check.

Checkpoint: run the class again. All five tests pass, and this one prints nothing.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-01 -Dtest=LoggingTest

You should see the logged requests and responses, followed by a result similar to the following:

1
2
3
4
5
6
7
[INFO] Running com.javanibble.module_01.section_05.LoggingTest
...
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.395 s -- in com.javanibble.module_01.section_05.LoggingTest
[INFO]
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

JUnit doesn’t promise an order for the tests in a class, so the logs may appear in a different order from the code.

Make a Test Fail

Change equalTo("acc-1001") to equalTo("acc-1002") in logOnlyWhenSomethingFails and run the command again. This time the held-back logs are printed, followed by the failure:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Request method:	GET
Request URI:	http://localhost:56123/api/v1/accounts/acc-1001
...
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
...

{
    "id": "acc-1001",
    ...
}

[ERROR] Failures:
[ERROR]   LoggingTest.logOnlyWhenSomethingFails:82 1 expectation failed.
JSON path id doesn't match.
Expected: acc-1002
  Actual: acc-1001

The failure says the id was wrong, and the log shows why: the request went to acc-1001, so the test, not the API, has the wrong expectation.

Change equalTo("acc-1002") back to equalTo("acc-1001") and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
A log().all() after then() prints nothing when the test failsIt’s placed after the check that failed, so it’s never reachedMove log() straight after then(), before any check
The build output is too long to readEvery test uses log().all()Use log().ifValidationFails() in the suites you keep
An Authorization header or session cookie appears in the CI logRequest logs print every header and cookieLog on failure only, and mask sensitive headers as shown in Module 5

Try It Yourself

Exercise 1: Log a Filtered URL

Add a test called logTheUriOfAFilteredList that requests /accounts with the query parameter currency=GBP. Log only the request URI and the response body, and check that count is 1.

Hint

Start from logOnlyParts. Keep log().uri() before when() and log().body() after then(), and drop the other log() calls.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
@Test
void logTheUriOfAFilteredList() {
    accountsApi()
        .queryParam("currency", "GBP")
        .log().uri()
    .when()
        .get("/accounts")
    .then()
        .log().body()
        .statusCode(200)
        .body("count", equalTo(1));
}

The log shows Request URI: http://localhost:<port>/api/v1/accounts?currency=GBP, followed by a body with one account, acc-1004.

Exercise 2: Log Little, Only on Failure

Add a test called logOnlyTheUriAndBodyWhenSomethingFails that requests the unknown account acc-9999 and checks that the status code is 404 and the title is "Not Found". If a check fails, the test should print only the request URI and the response body. Then change the expected title to "Gone" and confirm that exactly those two parts are printed.

Hint

ifValidationFails(..) takes a LogDetail on both the request and the response side. Use LogDetail.URI for the request and LogDetail.BODY for the response.

Solution
1
2
3
4
5
6
7
8
9
10
11
@Test
void logOnlyTheUriAndBodyWhenSomethingFails() {
    accountsApi()
        .log().ifValidationFails(LogDetail.URI)
    .when()
        .get("/accounts/{id}", "acc-9999")
    .then()
        .log().ifValidationFails(LogDetail.BODY)
        .statusCode(404)
        .body("title", equalTo("Not Found"));
}

With the title changed to "Gone", the log shows only the Request URI line and the problem details body, followed by Expected: Gone and Actual: Not Found.

Summary

You built LoggingTest, which prints requests and responses in full, in parts, only on failure and only for certain status codes. The next time a test fails on the build server, the log shows where the request went and what came back.

  • log() before when() logs the request, and log() after then() logs the response.
  • log().all() prints everything, and single parts such as uri() or body() keep the output short.
  • log().ifValidationFails() prints nothing while a test passes, so use it in the suites you keep.
  • log().ifError() and log().ifStatusCodeIsEqualTo(..) print only for error or specific status codes.
  • log() writes to standard out and includes every header, so keep credentials out of shared build logs.

Here are the commands you used in this guide:

1
mvn test -pl module-01 -Dtest=LoggingTest

What’s Next

Next: continue with Read REST Assured Failure Messages, which explains the shape of a failure message and why a then() chain stops at its first failure.

The code:

Go deeper:

Related guides:

This post is licensed under CC BY 4.0 by the author.