Write Request and Response Filters in REST Assured
Change every request and see every response in one place, covering a filter class, a lambda filter, a filter that records responses, a filter that fails a test, OrderedFilter, filters in a specification, and global filters.
The partner API wants an X-Correlation-Id on every request, and it echoes the id back so that both sides can trace a call through their logs. You could add a header line to fifty tests, and a check that the response echoes it, but the one test that forgets is the one that matters. A request specification holds fixed values, and this needs a fresh value per request and a look at the response. In this guide, you’ll write a filter that does both, and learn where to put it so every test gets it.
Level: Advanced · Time: 25 minutes · Part of: Module 8: Filters and Extensibility, section 1
What You’ll Build
You’ll build a filter called CorrelationIdFilter, and a test class called WritingFiltersTest with eight tests. The tests show the API refusing a request without a correlation id, the filter fixing it, filters written as lambdas, a filter that records responses and one that fails a test, the order of filters, and filters in a specification and globally.
With the filter in place, every request gets an id, and the API echoes it:
1
2
3
4
5
6
7
8
9
10
GET /api/v1/partner/accounts HTTP/1.1
Host: localhost:<port>
X-API-Key: partner-key-123
X-Correlation-Id: 3f1c2a9e-5b7d-4e0a-9c61-8d2f4b7a1e05
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
X-Correlation-Id: 3f1c2a9e-5b7d-4e0a-9c61-8d2f4b7a1e05
[{"id":"acc-1001","iban":"NL91ABNA0417164300"}]
When you’re done, Maven reports eight passing tests:
1
2
[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- Write a filter.
- See and check the response in a filter.
- Control the order of filters.
- Choose where filters go.
What You Need
- About 25 minutes
- JDK 26 or later
- Maven 3.9 or later
- An IDE (IntelliJ IDEA, VS Code or Eclipse)
- Knowledge: you can build a
RequestSpecificationwithRequestSpecBuilder, as taught in Build Reusable Request Specifications in REST Assured, and you know why static defaults onRestAssuredneed resetting, from Control Where REST Assured Requests Go. You should be comfortable with Java lambdas and records.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: this is the first section of Module 8, so you start from scratch. Create
WritingFiltersTestin themodule-08test sources and follow every heading below. - Skip ahead: open the finished class (
WritingFiltersTest.java) and read along. You can run it at any time with the command in Run the Tests.
Get the code: clone the examples repository and change into it:
1
2
git clone https://github.com/javanibble/rest-assured-examples.git
cd rest-assured-examples
If you’ve already cloned it for an earlier module, run git pull instead.
Out of scope: this guide doesn’t cover the filters REST Assured ships with, signing requests, or custom authentication; they’re taught in section 2, section 3 and section 4.
Understand Filters
The problem. Some work must happen on every request: a correlation id, a signature, a log line, a check that the response keeps a rule. Copying it into each test means many copies and one that’s missing. A request specification can hold fixed headers, but it can’t compute a new value per request, and it can’t look at the response.
The concept. A filter sits between the test and the network. Filter is an interface with one method:
1
2
3
Response filter(FilterableRequestSpecification request,
FilterableResponseSpecification responseSpec,
FilterContext context);
requestis the request about to be sent. The filter can read it and change its headers, body and parameters.context.next(request, responseSpec)runs the remaining filters and sends the request, and returns the response.- The return value is the response REST Assured goes on with, usually the one from
context.next(..).
Code before context.next(..) changes the request, and code after it sees the response. You can add a filter in three places:
| Where | How | Applies to |
|---|---|---|
| One request | given().filter(..) | That request |
| A specification | RequestSpecBuilder.addFilter(..) | Every request that uses the specification |
| Globally | RestAssured.filters(..) | Every request, until RestAssured.reset() |
When to use each. Use a filter for work that every request in a group needs, or a rule that every response must keep. Put it in a specification in most cases, on one request when only that test needs it, and globally only with a reset() to undo it.
Put work that every request needs in a filter, once, instead of in every test.
Meet the API Under Test
Module 8 tests SignedPaymentsApi, a payments API that requires signed requests. This section uses two of its endpoints:
| Request | Rules |
|---|---|
GET /api/v1/partner/accounts | Needs X-API-Key: partner-key-123 and an X-Correlation-Id, which it echoes in the response |
GET /api/v1/legacy/fx-rates | No rules, and it doesn’t echo the correlation id, like some old systems |
Without a correlation id, the partner endpoint refuses with a problem detail:
1
{"type":"about:blank","title":"Bad Request","status":400,"detail":"The header X-Correlation-Id is required","instance":"/api/v1/partner/accounts"}
Without the API key, it answers 401 with A valid X-API-Key is required. With both, it answers 200 with one account, [{"id":"acc-1001","iban":"NL91ABNA0417164300"}].
Your tests check these values:
- The status:
400without a correlation id,200with one. - The
X-Correlation-Idresponse header, which must match the one sent. - What the filters themselves recorded: statuses, and the order they ran in.
Write a Filter
Set Up the Test Class
Goal: create the test class with the API and a helper for requests to the partner endpoint.
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
36
37
38
39
40
41
42
43
44
45
46
47
package com.javanibble.module_08.section_01;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.javanibble.module_08.support.CorrelationIdFilter;
import com.javanibble.signing.SignedPaymentsApi;
import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.filter.OrderedFilter;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;
import io.restassured.specification.RequestSpecification;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class WritingFiltersTest {
private static SignedPaymentsApi api;
@BeforeAll
static void startApi() {
api = SignedPaymentsApi.start();
}
@AfterAll
static void stopApi() {
api.close();
}
private static RequestSpecification partnerApi() {
return given().baseUri(api.baseUri()).port(api.port()).header("X-API-Key", SignedPaymentsApi.PARTNER_API_KEY);
}
}
What’s happening:
SignedPaymentsApi.start()starts the API on a free port, andclose()stops it.partnerApi()sets the base URI, the port and the API key, but no correlation id: that’s the filter’s job.
Checkpoint: the class doesn’t compile yet, because CorrelationIdFilter doesn’t exist. You’ll write it next.
Write the Correlation Id Filter
Goal: write a filter that adds a correlation id before the request, and checks the echo after the response.
Create this class in a support package, where the later sections of the module reuse it:
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
package com.javanibble.module_08.support;
import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;
import java.util.UUID;
public final class CorrelationIdFilter implements Filter {
public static final String HEADER = "X-Correlation-Id";
@Override
public Response filter(FilterableRequestSpecification request, FilterableResponseSpecification responseSpec,
FilterContext context) {
if (!request.getHeaders().hasHeaderWithName(HEADER)) {
request.header(HEADER, UUID.randomUUID().toString());
}
String sent = request.getHeaders().getValue(HEADER);
Response response = context.next(request, responseSpec); // send the request (and run later filters)
if (!sent.equals(response.header(HEADER))) {
throw new AssertionError("Expected the response to echo " + HEADER + " " + sent
+ " but it was " + response.header(HEADER));
}
return response;
}
}
What’s happening:
- Before sending, the filter adds a fresh UUID as the correlation id, unless the test already set one.
context.next(request, responseSpec)sends the request and returns the response.- After the response, the filter checks that the API echoed the same id, and throws an
AssertionErrorif not.
Checkpoint: the project compiles. There are no tests yet, so there’s nothing to run until the next step.
See the API Refuse, Then Add the Filter
Goal: prove the request fails without a correlation id, and passes with the filter.
Add these tests to WritingFiltersTest:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
void withoutACorrelationIdTheApiRefuses() {
partnerApi().when().get("/api/v1/partner/accounts").then().statusCode(400);
}
@Test
void aFilterAddsIt() {
partnerApi()
.filter(new CorrelationIdFilter())
.when()
.get("/api/v1/partner/accounts")
.then()
.statusCode(200)
.body("$", hasSize(1));
}
What’s happening:
- Without the filter, the request has no
X-Correlation-Id, and the API answers400. filter(..)adds the filter to this request only. The test itself never mentions the header, and still gets a200and one account.
Checkpoint: run WritingFiltersTest from your IDE. Two tests pass.
Always call
context.next(..)and return its response. A filter that returnsnullwithout calling it never sends the request, and the test fails withNullPointerException: Cannot invoke "io.restassured.response.Response.then()" because the return value of ... get(String, Object[]) is null.
See and Check the Response
Write a Filter as a Lambda
Goal: write a short filter inline.
Add this test to the class:
1
2
3
4
5
6
7
8
9
10
11
12
@Test
void aFilterCanBeALambda() {
partnerApi()
.filter((request, responseSpec, context) -> {
request.header("X-Correlation-Id", "from-a-lambda");
return context.next(request, responseSpec);
})
.when()
.get("/api/v1/partner/accounts")
.then()
.header("X-Correlation-Id", equalTo("from-a-lambda"));
}
What’s happening:
Filterhas one abstract method, so a lambda can implement it.- The lambda sets a fixed correlation id and passes the request on, and the API echoes it back.
Checkpoint: run the class again. Three tests pass.
Record Every Response
Goal: use code after context.next(..) to see each response.
Add this test to the class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void aFilterSeesTheResponse() {
List<Integer> statuses = new ArrayList<>();
Filter recorder = (request, responseSpec, context) -> {
Response response = context.next(request, responseSpec);
statuses.add(response.statusCode());
return response;
};
partnerApi().filter(recorder).when().get("/api/v1/partner/accounts");
partnerApi().filter(recorder).header("X-Correlation-Id", "x").when().get("/api/v1/partner/accounts");
assertEquals(List.of(400, 200), statuses);
}
What’s happening:
- The recorder sends the request first, then adds the response’s status to a list.
- The same filter instance serves both requests: the first has no correlation id and gets
400, the second gets200. - Timing and logging filters, in the next section, work the same way.
Checkpoint: run the class again. Four tests pass.
Fail a Test From a Filter
Goal: show the filter’s own check failing against an endpoint that breaks the rule.
Add this test to the class:
1
2
3
4
5
6
7
8
9
10
11
@Test
void aFilterCanFailTheTest() {
// The legacy endpoint doesn't echo the correlation id, so CorrelationIdFilter's own check fails.
AssertionError error = assertThrows(AssertionError.class, () ->
given().baseUri(api.baseUri()).port(api.port())
.filter(new CorrelationIdFilter())
.when()
.get("/api/v1/legacy/fx-rates"));
assertTrue(error.getMessage().contains("to echo X-Correlation-Id"), error.getMessage());
}
What’s happening:
- The legacy endpoint answers
200but doesn’t echo the id, so the filter throwsExpected the response to echo X-Correlation-Id <id> but it was null. - The error is thrown inside
get(..), before anythen()could run. - A filter is the right place for a check that must hold for every response, and that no test should have to remember.
Checkpoint: run the class again. Five tests pass.
A filter’s check runs on every endpoint it’s applied to. Put a strict filter like this one in a specification for the endpoints that keep the rule, and leave it off requests to endpoints, like the legacy one, that don’t.
Control the Order of Filters
Order Filters With OrderedFilter
Goal: make the order of two filters explicit, whatever order they were added in.
Add this record and this test to the class:
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
@Test
void orderedFiltersRunInOrderOfTheirValue() {
List<String> calls = new ArrayList<>();
partnerApi()
.filter(new Named("second", 20, calls)) // added first ...
.filter(new Named("first", 10, calls)) // ... but the lower order runs first
.filter(new CorrelationIdFilter())
.when()
.get("/api/v1/partner/accounts");
assertEquals(List.of("first", "second"), calls);
}
/** Records its name when it runs. */
private record Named(String name, int order, List<String> calls) implements OrderedFilter {
@Override
public int getOrder() {
return order;
}
@Override
public Response filter(FilterableRequestSpecification request, FilterableResponseSpecification responseSpec,
FilterContext context) {
calls.add(name);
return context.next(request, responseSpec);
}
}
What’s happening:
OrderedFilteraddsgetOrder()toFilter. Lower values run first.Namedrecords its name when it runs. Thesecondfilter is added first, butfirsthas the lower order, so it runs first.- Ordinary filters count as
OrderedFilter.DEFAULT_PRECEDENCE, which is1000, and run in the order they were added.
Checkpoint: run the class again. Six tests pass.
Order matters most for a filter that must see the final request, such as a signer, which has to run after every filter that changes a header. Give it an order near
OrderedFilter.LOWEST_PRECEDENCE, so it runs last.
Choose Where Filters Go
Add a Filter to a Specification
Goal: give every request that uses a specification the filter.
Add this test to the class:
1
2
3
4
5
6
7
8
9
10
@Test
void filtersInASpecification() {
RequestSpecification spec = new RequestSpecBuilder()
.setBaseUri(api.baseUri()).setPort(api.port())
.addHeader("X-API-Key", SignedPaymentsApi.PARTNER_API_KEY)
.addFilter(new CorrelationIdFilter())
.build();
given(spec).when().get("/api/v1/partner/accounts").then().statusCode(200);
}
What’s happening:
addFilter(..)puts the filter in the specification, next to the base URI and the API key.- Every test that starts from
given(spec)gets the filter, and nothing is global.
Checkpoint: run the class again. Seven tests pass.
Add a Filter Globally
Goal: apply a filter to every request, and undo it afterwards.
Add this test to the class:
1
2
3
4
5
6
7
8
9
@Test
void globalFiltersApplyToEveryRequest() {
RestAssured.filters(new CorrelationIdFilter());
try {
partnerApi().when().get("/api/v1/partner/accounts").then().statusCode(200);
} finally {
RestAssured.reset(); // global state: always undo it
}
}
What’s happening:
RestAssured.filters(..)adds the filter to a static list that every request uses, sopartnerApi()gets it without asking.- It’s global state, with the same risks as the other static defaults:
RestAssured.reset()in afinallyblock undoes it, even when the test fails.
Checkpoint: run the class again. All eight tests pass.
Global filters pile up. Each
RestAssured.filters(..)call adds to the list, so adding the same filter twice runs it twice on every request. Prefer a specification, and always reset global filters.
Run the Tests
Run the following command from the repository root:
1
mvn test -pl module-08 -Dtest=WritingFiltersTest
You should see a result similar to the following:
1
2
3
4
5
6
[INFO] Running com.javanibble.module_08.section_01.WritingFiltersTest
[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.259 s -- in com.javanibble.module_08.section_01.WritingFiltersTest
[INFO]
[INFO] Tests run: 8, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Make a Test Fail
In aFilterAddsIt, delete the .filter(new CorrelationIdFilter()) line and run the command again. You should see a result similar to the following:
1
2
3
[ERROR] Failures:
[ERROR] WritingFiltersTest.aFilterAddsIt:68 1 expectation failed.
Expected status code <200> but was <400>.
Without the filter, nothing adds the correlation id, and the API refuses the request. The test never mentioned the header, which is the point of the filter, and also why a missing filter can be hard to spot: look at what the request specification and its filters add, not only at the test.
Put the .filter(..) line back and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
NullPointerException on then() | The filter returned null without calling context.next(..) | Call context.next(request, responseSpec) and return its response |
| A header set in a filter never reaches the server | It was set after context.next(..), when the request had already been sent | Change the request before context.next(..) |
| A filter runs twice on every request | It was added globally twice, or both globally and in a specification | Add it in one place, and call RestAssured.reset() after global filters |
| Filters run in an unexpected order | Ordinary filters run in the order they were added, which depends on where the specification is applied | Implement OrderedFilter and return an explicit order |
Try It Yourself
Exercise 1: Add the API Key With a Filter
Add a test called aFilterCanAddTheApiKey. Build a specification with only the base URI, the port and CorrelationIdFilter, and check that a request with it gets 401. Then add a lambda filter that sets X-API-Key to SignedPaymentsApi.PARTNER_API_KEY, and check that the same request gets 200.
Hint
Build the specification with RequestSpecBuilder and addFilter(..), without addHeader(..). Add the lambda with given(spec).filter(..), and call request.header(..) before context.next(..).
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void aFilterCanAddTheApiKey() {
RequestSpecification spec = new RequestSpecBuilder()
.setBaseUri(api.baseUri()).setPort(api.port())
.addFilter(new CorrelationIdFilter())
.build();
Filter apiKey = (request, responseSpec, context) -> {
request.header("X-API-Key", SignedPaymentsApi.PARTNER_API_KEY);
return context.next(request, responseSpec);
};
given(spec).when().get("/api/v1/partner/accounts").then().statusCode(401);
given(spec).filter(apiKey).when().get("/api/v1/partner/accounts").then().statusCode(200);
}
Exercise 2: Place a Filter Around the Default Order
Add a test called orderedFiltersAroundAnOrdinaryOne. Add a Named filter called late with order 1001, then an ordinary lambda filter that records plain, then a Named filter called early with order 999, and CorrelationIdFilter. Check that the calls are early, plain, late.
Hint
Ordinary filters count as 1000. Let the lambda add "plain" to the same calls list that Named uses.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Test
void orderedFiltersAroundAnOrdinaryOne() {
List<String> calls = new ArrayList<>();
partnerApi()
.filter(new Named("late", 1001, calls))
.filter((request, responseSpec, context) -> {
calls.add("plain");
return context.next(request, responseSpec);
})
.filter(new Named("early", 999, calls))
.filter(new CorrelationIdFilter())
.when()
.get("/api/v1/partner/accounts")
.then()
.statusCode(200);
assertEquals(List.of("early", "plain", "late"), calls);
}
Summary
You built CorrelationIdFilter, which adds a correlation id to every request and checks the echo on every response, and WritingFiltersTest, which uses it per request, in a specification and globally, next to lambda filters, a recorder and ordered filters. Not one test sets the correlation id header by hand, and none can forget the echo check.
- A filter gets the request, the response specification and a
FilterContext;context.next(..)sends the request and returns the response. - Code before
context.next(..)changes the request, and code after it sees the response and may fail the test. - A filter can be a class or a lambda, added per request with
filter(..), in a specification withaddFilter(..), or globally withRestAssured.filters(..). OrderedFiltermakes the order explicit: lower values run first, and ordinary filters count as1000.- Put shared filters in a specification, and undo global ones with
RestAssured.reset().
Here are the commands you used in this guide:
1
2
git clone https://github.com/javanibble/rest-assured-examples.git
mvn test -pl module-08 -Dtest=WritingFiltersTest
What’s Next
Next: continue with Write Timing, Masking and Repair Filters in REST Assured, which builds timing and logging filters, including one that masks personal data in the logs.
The code:
- The finished test class:
WritingFiltersTest.java - The filter:
CorrelationIdFilter.java - The code and run commands for this module: Module 8 README
Go deeper:
- REST Assured Usage wiki, for the Filters section and the filters REST Assured ships with.
- The
FilterJavadoc, for the interface andFilterContext. - W3C Trace Context, the standard form of the correlation ids that tie a call together across services.
Related guides:
- Build Reusable Request Specifications in REST Assured, for the specifications that hold shared filters.
- Control Where REST Assured Requests Go, for the static defaults that global filters share their risks with.
