CUSTOM FILTERS & INTERCEPTION: REQUEST/RESPONSE HOOKS & AUTH REFRESH

Architect enterprise-level HTTP interceptors and middleware in REST Assured: The Filter and OrderedFilter interfaces, FilterableRequestSpecification mutations, FilterableResponseSpecification audits, automated token re-authentication (401 interceptor loop), latency benchmarking, PII data masking, and Allure reporting listeners.

πŸͺ Wire Interception, Middleware Pipelines & Aspect-Oriented Testing

In enterprise API automation suites, cross-cutting concernsβ€”such as distributed correlation tracing, PII payload redaction, automated OAuth2 token refresh cycles, and HTML report loggingβ€”must not clutter business-level test scripts. Attempting to manage authentication retries or audit telemetry inside each individual test method violates separation of concerns and leads to high code duplication. REST Assured Filters provide a powerful interception and middleware mechanism based on the Chain of Responsibility pattern. By implementing the io.restassured.filter.Filter or OrderedFilter interfaces, test architects intercept outbound FilterableRequestSpecification objects prior to socket dispatch and capture inbound Response instances before assertion evaluation. This enables automated token refreshment on 401 Unauthorized responses, latency benchmarking, and seamless attachment of request/response bodies to Allure Reports.

1. REST Assured Filter Chain of Responsibility Topography
The architectural pipeline of REST Assured's filter execution chain, illustrating how outbound requests pass sequentially through ordered interceptors and inbound responses flow back up the filter stack.
Filter Interception & Context Delegation Topography
FILTER CHAIN OF RESPONSIBILITY EXECUTION TOPOGRAPHY:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ TEST PIPELINE TRIGGER: given().filter(filterA).filter(filterB).when().get("/students")        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                                                β–Ό (Outbound Request Interception)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ FILTER A: Correlation & Timing Interceptor (OrderedFilter - Priority: 1)                      β”‚
β”‚  β”œβ”€β”€ Injects X-Correlation-ID header into FilterableRequestSpecification                      β”‚
β”‚  β”œβ”€β”€ Captures System.currentTimeMillis()                                                      β”‚
β”‚  └── Invokes ctx.next(requestSpec, responseSpec) ──► Passes downstream                        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                                                β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ FILTER B: Security Token & PII Masking Interceptor (OrderedFilter - Priority: 2)              β”‚
β”‚  β”œβ”€β”€ Inspects request body; masks sensitive passwords or credit card numbers                  β”‚
β”‚  β”œβ”€β”€ Attaches Bearer JWT authentication header                                                β”‚
β”‚  └── Invokes ctx.next(requestSpec, responseSpec) ──► Passes downstream                        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                                                β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ WIRE SOCKET DISPATCH: Ingress HTTP Connection (Apache HttpClient)                             β”‚
β”‚ Dispatches HTTP GET /v1/students ──► Receives HTTP Response Packet                            β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                                                β–Ό (Inbound Response Interception Bubble-Up)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ FILTER B (Return Phase): Evaluates Response Status                                            β”‚
β”‚  └── If status == 401 Unauthorized: Acquires new OAuth token & re-executes request            β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                                                β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ FILTER A (Return Phase): Evaluates Response Performance                                       β”‚
β”‚  β”œβ”€β”€ Calculates total elapsed round-trip time: (System.currentTimeMillis() - start)           β”‚
β”‚  └── Attaches wire transcripts to Allure / Extent Reports                                     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                                β”‚
                                                β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ TERMINAL THEN PHASE: .then().statusCode(200).body(...)                                        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Architectural Standard: Filters follow the Chain of Responsibility pattern. Invoking FilterContext.next(requestSpec, responseSpec) delegates execution to the next filter in line or dispatches the actual HTTP call. Modifying the requestSpec before this call mutates outbound data, while inspecting the returned Response allows auditing inbound data.
Real-Time Example 1: Basic Request/Response Logging Filter
Implementing the core Filter interface. Demonstrates intercepting outbound request URIs, headers, and inbound response status codes to build a clean console audit logger.
Java (ConsoleAuditFilter.java Implementing Filter Interface)
package com.nikita.restassured.filters;

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;

public class ConsoleAuditFilter implements Filter {

    @Override
    public Response filter(FilterableRequestSpecification requestSpec,
                           FilterableResponseSpecification responseSpec,
                           FilterContext ctx) {

        // -------------------------------------------------------------
        // PRE-EXECUTION: Intercept and inspect outbound request
        // -------------------------------------------------------------
        System.out.println("\n═════════════════════ [OUTBOUND REQUEST] ═════════════════════");
        System.out.println("HTTP Method : " + requestSpec.getMethod());
        System.out.println("Target URI  : " + requestSpec.getURI());
        System.out.println("Headers     : " + requestSpec.getHeaders());
        if (requestSpec.getBody() != null) {
            System.out.println("Body        : " + requestSpec.getBody().toString());
        }
        System.out.println("══════════════════════════════════════════════════════════════");

        // Delegate execution down the filter chain to dispatch HTTP wire call
        Response response = ctx.next(requestSpec, responseSpec);

        // -------------------------------------------------------------
        // POST-EXECUTION: Intercept and inspect inbound response
        // -------------------------------------------------------------
        System.out.println("\n═════════════════════ [INBOUND RESPONSE] ═════════════════════");
        System.out.println("Status Code : " + response.getStatusCode() + " " + response.getStatusLine());
        System.out.println("Latency     : " + response.getTime() + " ms");
        System.out.println("Content-Type: " + response.getContentType());
        System.out.println("══════════════════════════════════════════════════════════════\n");

        // Return original response back to REST Assured validation pipeline
        return response;
    }
}
Filter Lifecycle Note: The filter method receives FilterableRequestSpecification, FilterableResponseSpecification, and FilterContext. You must return a Response object (either the original from ctx.next() or a modified one) for the test pipeline to continue.
Real-Time Example 2: Binding Custom Filters (Ad-Hoc, Spec & Global)
Applying custom filters across three distinct scope levels: ad-hoc per request via filter(), centralized across a RequestSpecBuilder, or registered globally via RestAssured.filters().
Java (Filter Registration Across Three Scopes)
package com.nikita.restassured.filters;

import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.RequestSpecification;
import org.testng.annotations.Test;

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

public class FilterScopeRegistrationTest {

    private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";

    // =========================================================================
    // SCOPE 1: AD-HOC PER-REQUEST FILTER ATTACHMENT
    // =========================================================================
    @Test(description = "Apply custom filter ad-hoc to a single specific test execution")
    public void testAdHocFilterAttachment() {
        given()
            .baseUri(BASE_URI)
            // Bind filter directly into Given statement
            .filter(new ConsoleAuditFilter())
            .pathParam("studentId", "STU-88219")
        .when()
            .get("/students/{studentId}")
        .then()
            .statusCode(200)
            .body("status", equalTo("SUCCESS"));

        System.out.println("[βœ”] Executed request with ad-hoc filter.");
    }

    // =========================================================================
    // SCOPE 2: CENTRALIZED ATTACHMENT VIA REQUESTSPECBUILDER
    // =========================================================================
    @Test(description = "Attach filter universally across a shared RequestSpecification")
    public void testSpecBuilderFilterAttachment() {
        RequestSpecification specWithFilter = new RequestSpecBuilder()
                .setBaseUri(BASE_URI)
                .addFilter(new ConsoleAuditFilter()) // Attached to reusable spec
                .build();

        given()
            .spec(specWithFilter)
        .when()
            .get("/students")
        .then()
            .statusCode(200);

        System.out.println("[βœ”] Executed request with RequestSpecification filter.");
    }

    // =========================================================================
    // SCOPE 3: GLOBAL REGISTRATION ACROSS THE ENTIRE JVM TEST RUNNER
    // =========================================================================
    public static void registerGlobalFilter() {
        // Registers filter for all subsequent given() calls throughout the entire project
        RestAssured.filters(new ConsoleAuditFilter());
        System.out.println("[*] Registered ConsoleAuditFilter globally into RestAssured.filters().");
    }
}
Console Audit Output: ═════════════════════ [OUTBOUND REQUEST] ═════════════════════ HTTP Method : GET Target URI : https://staging-api.nikita-infotech.com/v1/students/STU-88219 Headers : Accept=*/* ══════════════════════════════════════════════════════════════ ═════════════════════ [INBOUND RESPONSE] ═════════════════════ Status Code : 200 HTTP/1.1 200 OK Latency : 114 ms Content-Type: application/json; charset=utf-8 ══════════════════════════════════════════════════════════════
Real-Time Example 3: Automated Correlation & Tracing Header Injector
Enforcing distributed tracing standards across microservice architectures. Demonstrates mutating FilterableRequestSpecification dynamically to inject a unique UUID X-Correlation-ID on every outgoing call.
Java (CorrelationTracingFilter.java Dynamic Header Injector)
package com.nikita.restassured.filters;

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 org.testng.Assert;
import org.testng.annotations.Test;

import java.util.UUID;

import static io.restassured.RestAssured.given;

public class CorrelationTracingFilter implements Filter {

    public static final String CORRELATION_HEADER = "X-Correlation-ID";

    @Override
    public Response filter(FilterableRequestSpecification requestSpec,
                           FilterableResponseSpecification responseSpec,
                           FilterContext ctx) {

        // Check if correlation ID already exists; if not, generate a fresh unique UUID
        if (!requestSpec.getHeaders().hasHeaderWithName(CORRELATION_HEADER)) {
            String generatedCorrelationId = "TRACE-" + UUID.randomUUID().toString();
            // Mutate outbound request headers prior to wire dispatch:
            requestSpec.header(CORRELATION_HEADER, generatedCorrelationId);
            System.out.println("[*] Injected correlation header: " + generatedCorrelationId);
        }

        // Proceed with downstream filter chain
        return ctx.next(requestSpec, responseSpec);
    }
}

// ==============================================================================
// VERIFICATION TEST METHOD
// ==============================================================================
class TracingFilterTest {

    @Test(description = "Verify CorrelationTracingFilter automatically injects X-Correlation-ID")
    public void testAutomaticTracingInjection() {
        given()
            .baseUri("https://staging-api.nikita-infotech.com/v1")
            .filter(new CorrelationTracingFilter())
        .when()
            .get("/health")
        .then()
            .statusCode(200);

        System.out.println("[βœ”] Outbound request contained automatically injected correlation header.");
    }
}
Tracing Filter Output: [*] Injected correlation header: TRACE-8f9b10c9-bf12-4e89-a0bc-1123481029ba GET /v1/health -> HTTP 200 OK [48ms] Eliminates repetitive UUID generation in test classes; every outbound call carries tracing metadata.
Real-Time Example 4: Automated 401 Re-Authentication & Token Refresh Loop
Implementing resilient self-healing tests. Intercepts HTTP 401 Unauthorized responses, invokes a token generation endpoint to acquire fresh credentials, updates the session token, and re-executes the failed call automatically.
Java (TokenRenewalFilter.java Interceptor & Re-Execution Loop)
package com.nikita.restassured.filters;

import io.restassured.RestAssured;
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;

public class TokenRenewalFilter implements Filter {

    // Volatile shared token across concurrent test executions
    private static volatile String activeBearerToken = "EXPIRED_STALE_TOKEN_999";

    @Override
    public Response filter(FilterableRequestSpecification requestSpec,
                           FilterableResponseSpecification responseSpec,
                           FilterContext ctx) {

        // Step 1: Attach current active token to outbound request
        requestSpec.header("Authorization", "Bearer " + activeBearerToken);

        // Step 2: Dispatch request downstream
        Response response = ctx.next(requestSpec, responseSpec);

        // Step 3: Intercept 401 Unauthorized status indicating token expiration
        if (response.getStatusCode() == 401) {
            System.out.println("[!] Intercepted HTTP 401 Unauthorized. Refreshing expired OAuth token...");

            // Synchronize token acquisition to avoid thundering herd across threads
            synchronized (TokenRenewalFilter.class) {
                activeBearerToken = acquireNewBearerToken();
                System.out.println("[+] Successfully acquired fresh token: " + activeBearerToken.substring(0, 15) + "...");
            }

            // Step 4: Mutate request specification with the new valid token
            requestSpec.removeHeader("Authorization");
            requestSpec.header("Authorization", "Bearer " + activeBearerToken);

            // Step 5: Re-execute the exact same request using FilterContext
            System.out.println("[*] Re-executing original request with updated Bearer token...");
            response = ctx.next(requestSpec, responseSpec);
        }

        return response;
    }

    private String acquireNewBearerToken() {
        // Out-of-band call to authentication endpoint
        return RestAssured.given()
                .baseUri("https://auth.nikita-infotech.com")
                .contentType("application/x-www-form-urlencoded")
                .formParam("grant_type", "client_credentials")
                .formParam("client_id", "sdet-automation-worker")
                .formParam("client_secret", "Secret#Enterprise2026")
                .post("/oauth/v2/token")
                .then()
                .statusCode(200)
                .extract()
                .path("access_token");
    }
}
Token Renewal Telemetry: GET /v1/students/STU-88219 -> HTTP 401 Unauthorized [Authorization: Bearer EXPIRED_STALE_TOKEN_999] [!] Intercepted HTTP 401 Unauthorized. Refreshing expired OAuth token... [+] Successfully acquired fresh token: eyJhbGciOiJIUz... [*] Re-executing original request with updated Bearer token... GET /v1/students/STU-88219 -> HTTP 200 OK [128ms] Test passes transparently without failure; stale session was self-healed in-flight.
Real-Time Example 5: Performance Latency Benchmarking & SLA Logging Filter
Auditing execution duration across all API calls. Measures round-trip elapsed milliseconds, logs warnings on slow queries exceeding warning thresholds, and maintains telemetry logs for performance tracking.
Java (PerformanceBenchmarkingFilter.java Timing Interceptor)
package com.nikita.restassured.filters;

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;

public class PerformanceBenchmarkingFilter implements Filter {

    private final long warningThresholdMs;

    public PerformanceBenchmarkingFilter(long warningThresholdMs) {
        this.warningThresholdMs = warningThresholdMs;
    }

    public PerformanceBenchmarkingFilter() {
        this(800L); // Default 800ms SLA warning ceiling
    }

    @Override
    public Response filter(FilterableRequestSpecification requestSpec,
                           FilterableResponseSpecification responseSpec,
                           FilterContext ctx) {

        long startTime = System.currentTimeMillis();

        // Dispatch request downstream to server
        Response response = ctx.next(requestSpec, responseSpec);

        long elapsedTime = System.currentTimeMillis() - startTime;
        String endpoint = requestSpec.getMethod() + " " + requestSpec.getDerivedPath();

        if (elapsedTime > warningThresholdMs) {
            System.err.printf("[PERFORMANCE WARNING] %s took %d ms (Threshold: %d ms)%n",
                    endpoint, elapsedTime, warningThresholdMs);
        } else {
            System.out.printf("[PERFORMANCE SLA PASS] %s completed in %d ms%n", 
                    endpoint, elapsedTime);
        }

        return response;
    }
}
Benchmark Output: [PERFORMANCE SLA PASS] GET /v1/health completed in 42 ms [PERFORMANCE SLA PASS] GET /v1/students/STU-88219 completed in 118 ms [PERFORMANCE WARNING] GET /v1/students/analytics-aggregate took 1240 ms (Threshold: 800 ms) Allows test suites to track slow queries and highlight backend latency degradations in CI logs.
Real-Time Example 6: PII Data Masking Filter (Redacting Passwords & Cards)
Preventing sensitive data exposure in CI/CD build logs. Intercepts outbound JSON request payloads and masks passwords, credit card numbers, and authorization headers before printing to logs.
Java (PiiMaskingFilter.java Sensitive Data Redactor)
package com.nikita.restassured.filters;

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.regex.Pattern;

public class PiiMaskingFilter implements Filter {

    // Regex patterns for sensitive JSON keys
    private static final Pattern PASSWORD_PATTERN = Pattern.compile("(?i)(\"password\"\\s*:\\s*\")[^\"]+(\")");
    private static final Pattern CARD_PATTERN = Pattern.compile("(?i)(\"cardNumber\"\\s*:\\s*\")[^\"]+(\")");

    @Override
    public Response filter(FilterableRequestSpecification requestSpec,
                           FilterableResponseSpecification responseSpec,
                           FilterContext ctx) {

        System.out.println("[SECURITY SANITIZER] Outbound Request: " + requestSpec.getMethod() + " " + requestSpec.getURI());

        // Sanitize headers: Redact Authorization tokens in logs
        if (requestSpec.getHeaders().hasHeaderWithName("Authorization")) {
            System.out.println("  Header: Authorization = Bearer **********[REDACTED]**********");
        }

        // Sanitize body: Redact passwords and financial card numbers
        if (requestSpec.getBody() != null) {
            String rawBody = requestSpec.getBody().toString();
            String sanitizedBody = PASSWORD_PATTERN.matcher(rawBody).replaceAll("$1********[MASKED]$2");
            sanitizedBody = CARD_PATTERN.matcher(sanitizedBody).replaceAll("$1************1234[MASKED]$2");

            System.out.println("  Sanitized Payload: " + sanitizedBody);
        }

        // The actual unmasked request proceeds over the secure wire to the server:
        return ctx.next(requestSpec, responseSpec);
    }
}
Sanitized Log Output: [SECURITY SANITIZER] Outbound Request: POST https://staging-api.nikita-infotech.com/v1/auth/login Header: Authorization = Bearer **********[REDACTED]********** Sanitized Payload: {"username":"sdet-lead","password":"********[MASKED]"} Prevents plain-text passwords and credentials from leaking into Jenkins, GitHub Actions, or Allure logs.
Real-Time Example 7: Interceptor Ordering via OrderedFilter
Controlling execution sequence when chaining multiple filters. Implements OrderedFilter to define strict priority levels, ensuring logging and authentication interceptors run in the correct order.
Java (OrderedFilter Priority Management)
package com.nikita.restassured.filters;

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 org.testng.annotations.Test;

import static io.restassured.RestAssured.given;

// Interceptor 1: Runs FIRST (Lowest order value = Highest priority)
class PriorityOneTracingFilter implements OrderedFilter {
    @Override
    public int getOrder() {
        return 1; // Highest priority
    }

    @Override
    public Response filter(FilterableRequestSpecification req, FilterableResponseSpecification res, FilterContext ctx) {
        System.out.println("[Order 1] Executing Tracing Header Interceptor");
        req.header("X-Filter-Order-1", "Executed-First");
        return ctx.next(req, res);
    }
}

// Interceptor 2: Runs SECOND
class PriorityTwoAuthFilter implements OrderedFilter {
    @Override
    public int getOrder() {
        return 2; // Executes after Order 1
    }

    @Override
    public Response filter(FilterableRequestSpecification req, FilterableResponseSpecification res, FilterContext ctx) {
        System.out.println("[Order 2] Executing Auth Verification Interceptor");
        req.header("X-Filter-Order-2", "Executed-Second");
        return ctx.next(req, res);
    }
}

public class OrderedFilterExecutionTest {

    @Test(description = "Verify OrderedFilter enforces execution order based on getOrder() return value")
    public void testOrderedFiltersExecution() {
        given()
            .baseUri("https://staging-api.nikita-infotech.com/v1")
            // Registered in reverse order to prove OrderedFilter sorts by getOrder():
            .filter(new PriorityTwoAuthFilter())
            .filter(new PriorityOneTracingFilter())
        .when()
            .get("/health")
        .then()
            .statusCode(200);

        System.out.println("[βœ”] Verified filter chain executed in exact order (Priority 1 then Priority 2).");
    }
}
Execution Sequence Output: [Order 1] Executing Tracing Header Interceptor [Order 2] Executing Auth Verification Interceptor GET /v1/health -> HTTP 200 OK [38ms] OrderedFilter guarantees deterministic execution regardless of the order filters are passed to .filter().
Real-Time Example 8: Allure & Extent Reports Attachment Filter
Integrating test execution with HTML reporting dashboards. Demonstrates attaching request and response transcripts as collapsible attachments in Allure Reports using AllureRestAssured.
Java & XML: Allure Report Filter Attachment Setup
// ==============================================================================
// STEP 1: MAVEN DEPENDENCY REQUIRED (pom.xml)
// ==============================================================================
// <dependency>
//     <groupId>io.qameta.allure</groupId>
//     <artifactId>allure-rest-assured</artifactId>
//     <version>2.27.0</version>
//     <scope>test</scope>
// </dependency>

package com.nikita.restassured.filters;

import io.qameta.allure.restassured.AllureRestAssured;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.RequestSpecification;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

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

public class AllureReportingFilterTest {

    private RequestSpecification allureReportSpec;

    @BeforeClass
    public void setupAllureFilter() {
        // Instantiate AllureRestAssured filter with customized attachment templates
        AllureRestAssured allureFilter = new AllureRestAssured()
                .setRequestTemplate("http-request.ftl")
                .setResponseTemplate("http-response.ftl");

        allureReportSpec = new RequestSpecBuilder()
                .setBaseUri("https://staging-api.nikita-infotech.com/v1")
                .addFilter(allureFilter) // Attaches all wire packets directly to Allure test steps!
                .build();

        System.out.println("[*] AllureRestAssured attachment filter bound to RequestSpecification.");
    }

    @Test(description = "Execute request with automatic Allure report request/response attachments")
    public void testAllureAttachmentGeneration() {
        given()
            .spec(allureReportSpec)
            .pathParam("studentId", "STU-88219")
        .when()
            .get("/students/{studentId}")
        .then()
            .statusCode(200)
            .body("status", equalTo("SUCCESS"));

        System.out.println("[βœ”] Wire request and response saved to target/allure-results automatically.");
    }
}
Allure Telemetry Trace: [*] AllureRestAssured attachment filter bound to RequestSpecification. GET /v1/students/STU-88219 -> HTTP 200 OK [112ms] Created attachment: 'Request' (target/allure-results/c4f1a162-attachment.html) Created attachment: 'HTTP/1.1 200 OK' (target/allure-results/e8b2a091-attachment.html) Wire logs are visible as collapsible panels inside the Allure HTML dashboard.
Real-Time Example 9: Custom Filters Specification Reference Matrix
A comprehensive reference summary pairing filter interfaces, context methods, operational responsibilities, and best practices for REST Assured automation architects.
Filter & Interception Specification Reference Matrix
REST ASSURED FILTER & INTERCEPTION SPECIFICATION MATRIX:
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ INTERFACE / COMPONENT   β”‚ METHOD SIGNATURE             β”‚ RETURN TYPE      β”‚ PRIMARY OPERATIONAL PURPOSE   β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Filter                  β”‚ filter(reqSpec, resSpec, ctx)β”‚ Response         β”‚ Core interceptor contract     β”‚
β”‚ OrderedFilter           β”‚ getOrder()                   β”‚ int (Priority)   β”‚ Enforces filter run sequence  β”‚
β”‚ FilterContext           β”‚ ctx.next(reqSpec, resSpec)   β”‚ Response         β”‚ Dispatches to next in chain   β”‚
β”‚ FilterableRequestSpec   β”‚ reqSpec.header(name, value)  β”‚ RequestSpec      β”‚ Injects/mutates outbound data β”‚
β”‚ FilterableRequestSpec   β”‚ reqSpec.removeHeader(name)   β”‚ RequestSpec      β”‚ Strips expired headers        β”‚
β”‚ FilterableRequestSpec   β”‚ reqSpec.getURI()             β”‚ String (URI)     β”‚ Inspects target URL in logs   β”‚
β”‚ FilterableRequestSpec   β”‚ reqSpec.getBody()            β”‚ Object (Body)    β”‚ Accesses raw payload for PII  β”‚
β”‚ FilterableResponseSpec  β”‚ resSpec.hasHeaderAssertions()β”‚ Boolean          β”‚ Inspects response assertions  β”‚
β”‚ Response (Returned)     β”‚ response.getStatusCode()     β”‚ int (Status)     β”‚ Checks status for 401 retry   β”‚
β”‚ AllureRestAssured       β”‚ new AllureRestAssured()      β”‚ Filter instance  β”‚ Auto-attaches logs to Allure  β”‚
β”‚ RestAssured.filters()   β”‚ RestAssured.filters(f1, f2)  β”‚ void             β”‚ Registers global filter chain β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ TOP 5 CUSTOM FILTER BEST PRACTICES:                                                                       β”‚
β”‚ 1. Centralize cross-cutting concerns: Move correlation IDs, timing, and auth refresh into filters.        β”‚
β”‚ 2. Use OrderedFilter for deterministic execution: Control execution priority with getOrder().             β”‚
β”‚ 3. Implement self-healing 401 token refresh: Intercept 401s, fetch a fresh token, and retry in-flight.    β”‚
β”‚ 4. Mask sensitive PII in console logs: Redact passwords and tokens before printing to build logs.         β”‚
β”‚ 5. Attach AllureRestAssured for rich reporting: Provide full request/response wire logs to developers.    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Engineering Best Practice: Custom filters elevate REST Assured from a simple test runner into an aspect-oriented API testing framework. By centralizing distributed tracing, implementing self-healing token renewals on 401s, masking sensitive PII, and attaching transcripts to Allure, you build clean, resilient, and enterprise-ready test suites.