or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mdconfiguration.mdfilters-extensions.mdhttp-operations.mdindex.mdobject-mapping.mdrequest-building.mdresponse-validation.md

filters-extensions.mddocs/

0

# Filters and Extensions

1

2

Extensible filter system for request/response processing, logging, timing, session management, and custom behavior injection to enhance REST Assured functionality.

3

4

## Capabilities

5

6

### Filter Interface

7

8

Base interface for creating custom filters that can intercept and modify requests and responses.

9

10

```java { .api }

11

/**

12

* Base interface for REST Assured filters

13

*/

14

interface Filter {

15

/**

16

* Filter method called for each request/response cycle

17

* @param requestSpec Filterable request specification

18

* @param responseSpec Filterable response specification

19

* @param ctx Filter context for continuing the filter chain

20

* @return The response after filtering

21

*/

22

Response filter(FilterableRequestSpecification requestSpec,

23

FilterableResponseSpecification responseSpec,

24

FilterContext ctx);

25

}

26

27

/**

28

* Ordered filter interface with execution priority

29

*/

30

interface OrderedFilter extends Filter {

31

/**

32

* Get the order/priority of this filter (lower values execute first)

33

* @return Filter execution order

34

*/

35

int getOrder();

36

}

37

38

/**

39

* Filter context for continuing the filter chain

40

*/

41

interface FilterContext {

42

/**

43

* Continue with the next filter in the chain

44

* @param requestSpec Updated request specification

45

* @param responseSpec Updated response specification

46

* @return Response from the filter chain

47

*/

48

Response next(FilterableRequestSpecification requestSpec,

49

FilterableResponseSpecification responseSpec);

50

}

51

```

52

53

**Usage Examples:**

54

55

```java

56

// Custom filter implementation

57

public class TimingFilter implements Filter {

58

@Override

59

public Response filter(FilterableRequestSpecification requestSpec,

60

FilterableResponseSpecification responseSpec,

61

FilterContext ctx) {

62

long startTime = System.currentTimeMillis();

63

64

Response response = ctx.next(requestSpec, responseSpec);

65

66

long duration = System.currentTimeMillis() - startTime;

67

System.out.println("Request took: " + duration + "ms");

68

69

return response;

70

}

71

}

72

73

// Using custom filter

74

given()

75

.filter(new TimingFilter())

76

.when()

77

.get("/users")

78

.then()

79

.statusCode(200);

80

81

// Global filter

82

RestAssured.filters(new TimingFilter());

83

```

84

85

### Request Logging Filters

86

87

Filters for logging HTTP request details.

88

89

```java { .api }

90

/**

91

* Filter for logging HTTP requests

92

*/

93

class RequestLoggingFilter implements Filter {

94

/**

95

* Create request logging filter with default settings

96

*/

97

RequestLoggingFilter();

98

99

/**

100

* Create request logging filter with specific log detail

101

* @param logDetail Level of detail to log

102

*/

103

RequestLoggingFilter(LogDetail logDetail);

104

105

/**

106

* Create request logging filter with custom print stream

107

* @param printStream Stream to write log output to

108

*/

109

RequestLoggingFilter(PrintStream printStream);

110

111

/**

112

* Create request logging filter with detail and stream

113

* @param logDetail Level of detail to log

114

* @param printStream Stream to write log output to

115

*/

116

RequestLoggingFilter(LogDetail logDetail, PrintStream printStream);

117

118

/**

119

* Log request if status code matches predicate

120

* @param shouldLog Predicate to determine if request should be logged

121

* @return Request logging filter

122

*/

123

static RequestLoggingFilter logRequestTo(PrintStream printStream);

124

125

/**

126

* Log request if status code matches

127

* @param statusCode Status code to match for logging

128

* @return Request logging filter

129

*/

130

static RequestLoggingFilter logRequestIfStatusCodeIs(int statusCode);

131

132

/**

133

* Log request if status code matches any of the provided codes

134

* @param statusCodes Status codes to match for logging

135

* @return Request logging filter

136

*/

137

static RequestLoggingFilter logRequestIfStatusCodeMatches(Matcher<Integer> statusCodes);

138

}

139

```

140

141

**Usage Examples:**

142

143

```java

144

// Basic request logging

145

given()

146

.filter(new RequestLoggingFilter())

147

.when()

148

.get("/users");

149

150

// Log only headers and parameters

151

given()

152

.filter(new RequestLoggingFilter(LogDetail.HEADERS))

153

.when()

154

.post("/users");

155

156

// Conditional request logging

157

given()

158

.filter(RequestLoggingFilter.logRequestIfStatusCodeIs(500))

159

.when()

160

.get("/users");

161

162

// Log to custom stream

163

given()

164

.filter(new RequestLoggingFilter(System.err))

165

.when()

166

.get("/users");

167

```

168

169

### Response Logging Filters

170

171

Filters for logging HTTP response details.

172

173

```java { .api }

174

/**

175

* Filter for logging HTTP responses

176

*/

177

class ResponseLoggingFilter implements Filter {

178

/**

179

* Create response logging filter with default settings

180

*/

181

ResponseLoggingFilter();

182

183

/**

184

* Create response logging filter with specific log detail

185

* @param logDetail Level of detail to log

186

*/

187

ResponseLoggingFilter(LogDetail logDetail);

188

189

/**

190

* Create response logging filter with custom print stream

191

* @param printStream Stream to write log output to

192

*/

193

ResponseLoggingFilter(PrintStream printStream);

194

195

/**

196

* Create response logging filter with detail and stream

197

* @param logDetail Level of detail to log

198

* @param printStream Stream to write log output to

199

*/

200

ResponseLoggingFilter(LogDetail logDetail, PrintStream printStream);

201

202

/**

203

* Log response to specific print stream

204

* @param printStream Stream to write log output to

205

* @return Response logging filter

206

*/

207

static ResponseLoggingFilter logResponseTo(PrintStream printStream);

208

209

/**

210

* Log response if status code matches

211

* @param statusCode Status code to match for logging

212

* @return Response logging filter

213

*/

214

static ResponseLoggingFilter logResponseIfStatusCodeIs(int statusCode);

215

216

/**

217

* Log response if status code matches predicate

218

* @param statusCodes Status code matcher for logging

219

* @return Response logging filter

220

*/

221

static ResponseLoggingFilter logResponseIfStatus CodeMatches(Matcher<Integer> statusCodes);

222

223

/**

224

* Log response body if content type matches

225

* @param contentType Content type to match for logging

226

* @return Response logging filter

227

*/

228

static ResponseLoggingFilter logResponseIfContentTypeMatches(String contentType);

229

}

230

```

231

232

### Error Logging Filter

233

234

Filter for logging only error responses.

235

236

```java { .api }

237

/**

238

* Filter for logging error responses (4xx and 5xx status codes)

239

*/

240

class ErrorLoggingFilter implements Filter {

241

/**

242

* Create error logging filter with default settings

243

*/

244

ErrorLoggingFilter();

245

246

/**

247

* Create error logging filter with custom print stream

248

* @param printStream Stream to write error logs to

249

*/

250

ErrorLoggingFilter(PrintStream printStream);

251

252

/**

253

* Create error logging filter with specific log detail

254

* @param logDetail Level of detail to log for errors

255

*/

256

ErrorLoggingFilter(LogDetail logDetail);

257

258

/**

259

* Create error logging filter with detail and stream

260

* @param logDetail Level of detail to log

261

* @param printStream Stream to write error logs to

262

*/

263

ErrorLoggingFilter(LogDetail logDetail, PrintStream printStream);

264

265

/**

266

* Log errors to specific print stream

267

* @param printStream Stream to write error logs to

268

* @return Error logging filter

269

*/

270

static ErrorLoggingFilter logErrorsTo(PrintStream printStream);

271

}

272

```

273

274

### Session Management Filters

275

276

Filters for handling session cookies and session-based authentication.

277

278

```java { .api }

279

/**

280

* Filter for automatic session management via cookies

281

*/

282

class SessionFilter implements Filter {

283

/**

284

* Create session filter with default session ID cookie name

285

*/

286

SessionFilter();

287

288

/**

289

* Create session filter with custom session ID cookie name

290

* @param sessionIdName Name of the session ID cookie

291

*/

292

SessionFilter(String sessionIdName);

293

294

/**

295

* Get the current session ID

296

* @return Current session ID value

297

*/

298

String getSessionId();

299

300

/**

301

* Set the session ID

302

* @param sessionId Session ID to set

303

*/

304

void setSessionId(String sessionId);

305

}

306

```

307

308

**Usage Examples:**

309

310

```java

311

// Automatic session management

312

SessionFilter sessionFilter = new SessionFilter();

313

314

// Login to get session

315

given()

316

.filter(sessionFilter)

317

.formParam("username", "user")

318

.formParam("password", "password")

319

.when()

320

.post("/login")

321

.then()

322

.statusCode(200);

323

324

// Use session for subsequent requests

325

given()

326

.filter(sessionFilter) // Automatically includes session cookie

327

.when()

328

.get("/protected")

329

.then()

330

.statusCode(200);

331

332

// Custom session cookie name

333

SessionFilter customSessionFilter = new SessionFilter("CUSTOM_SESSION_ID");

334

```

335

336

### Cookie Management Filter

337

338

Filter for persistent cookie management across requests.

339

340

```java { .api }

341

/**

342

* Filter for managing cookies across multiple requests

343

*/

344

class CookieFilter implements Filter {

345

/**

346

* Create cookie filter

347

*/

348

CookieFilter();

349

350

/**

351

* Get all managed cookies

352

* @return Cookies object containing all cookies

353

*/

354

Cookies getCookies();

355

356

/**

357

* Get specific cookie value

358

* @param cookieName Name of the cookie

359

* @return Cookie value or null if not found

360

*/

361

String getCookieValue(String cookieName);

362

}

363

```

364

365

### Timing and Performance Filters

366

367

Filters for measuring request/response timing and performance.

368

369

```java { .api }

370

/**

371

* Filter for measuring request timing

372

*/

373

class TimingFilter implements Filter {

374

/**

375

* Create timing filter

376

*/

377

TimingFilter();

378

379

/**

380

* Get the last request duration in milliseconds

381

* @return Duration of last request in milliseconds

382

*/

383

long getTimeIn(TimeUnit timeUnit);

384

385

/**

386

* Get validation result including timing information

387

* @return Validation result with timing data

388

*/

389

ValidatableResponse and();

390

391

/**

392

* Validate response time

393

* @param matcher Matcher for response time validation

394

* @param timeUnit Time unit for the matcher

395

* @return Validatable response for chaining

396

*/

397

ValidatableResponse time(Matcher<Long> matcher, TimeUnit timeUnit);

398

}

399

```

400

401

**Usage Examples:**

402

403

```java

404

// Timing filter usage

405

TimingFilter timingFilter = new TimingFilter();

406

407

Response response = given()

408

.filter(timingFilter)

409

.when()

410

.get("/users")

411

.then()

412

.statusCode(200)

413

.time(lessThan(2000L), TimeUnit.MILLISECONDS)

414

.extract()

415

.response();

416

417

long duration = timingFilter.getTimeIn(TimeUnit.MILLISECONDS);

418

System.out.println("Request took: " + duration + "ms");

419

```

420

421

### Filter Configuration

422

423

Methods for configuring filters at request and global levels.

424

425

```java { .api }

426

// Request-level filter configuration

427

interface RequestSpecification {

428

/**

429

* Add a filter to this request

430

* @param filter Filter to add

431

* @return Updated request specification

432

*/

433

RequestSpecification filter(Filter filter);

434

435

/**

436

* Add multiple filters to this request

437

* @param filters List of filters to add

438

* @return Updated request specification

439

*/

440

RequestSpecification filters(List<Filter> filters);

441

442

/**

443

* Add filters to this request

444

* @param filter First filter to add

445

* @param additionalFilters Additional filters to add

446

* @return Updated request specification

447

*/

448

RequestSpecification filters(Filter filter, Filter... additionalFilters);

449

}

450

451

// Global filter configuration (static methods in RestAssured)

452

/**

453

* Add filters to be applied to all requests

454

* @param filters List of filters to add globally

455

*/

456

static void filters(List<Filter> filters);

457

458

/**

459

* Add filters to be applied to all requests

460

* @param filter First filter to add globally

461

* @param additionalFilters Additional filters to add globally

462

*/

463

static void filters(Filter filter, Filter... additionalFilters);

464

465

/**

466

* Replace all existing global filters with new filters

467

* @param filters List of filters to set as global filters

468

*/

469

static void replaceFiltersWith(List<Filter> filters);

470

471

/**

472

* Replace all existing global filters with new filters

473

* @param filter First filter to set

474

* @param additionalFilters Additional filters to set

475

*/

476

static void replaceFiltersWith(Filter filter, Filter... additionalFilters);

477

478

/**

479

* Get current list of global filters

480

* @return Unmodifiable list of current global filters

481

*/

482

static List<Filter> filters();

483

```

484

485

### Custom Filter Examples

486

487

Examples of implementing custom filters for specific use cases.

488

489

**Authorization Header Filter:**

490

491

```java

492

public class AuthorizationFilter implements Filter {

493

private final String token;

494

495

public AuthorizationFilter(String token) {

496

this.token = token;

497

}

498

499

@Override

500

public Response filter(FilterableRequestSpecification requestSpec,

501

FilterableResponseSpecification responseSpec,

502

FilterContext ctx) {

503

requestSpec.header("Authorization", "Bearer " + token);

504

return ctx.next(requestSpec, responseSpec);

505

}

506

}

507

```

508

509

**Request ID Filter:**

510

511

```java

512

public class RequestIdFilter implements Filter {

513

@Override

514

public Response filter(FilterableRequestSpecification requestSpec,

515

FilterableResponseSpecification responseSpec,

516

FilterContext ctx) {

517

String requestId = UUID.randomUUID().toString();

518

requestSpec.header("X-Request-ID", requestId);

519

520

Response response = ctx.next(requestSpec, responseSpec);

521

522

System.out.println("Request ID: " + requestId +

523

", Status: " + response.getStatusCode());

524

return response;

525

}

526

}

527

```

528

529

**Retry Filter:**

530

531

```java

532

public class RetryFilter implements Filter {

533

private final int maxRetries;

534

private final long delayMs;

535

536

public RetryFilter(int maxRetries, long delayMs) {

537

this.maxRetries = maxRetries;

538

this.delayMs = delayMs;

539

}

540

541

@Override

542

public Response filter(FilterableRequestSpecification requestSpec,

543

FilterableResponseSpecification responseSpec,

544

FilterContext ctx) {

545

Response response = null;

546

Exception lastException = null;

547

548

for (int attempt = 0; attempt <= maxRetries; attempt++) {

549

try {

550

response = ctx.next(requestSpec, responseSpec);

551

if (response.getStatusCode() < 500) {

552

return response; // Success or client error

553

}

554

} catch (Exception e) {

555

lastException = e;

556

}

557

558

if (attempt < maxRetries) {

559

try {

560

Thread.sleep(delayMs);

561

} catch (InterruptedException e) {

562

Thread.currentThread().interrupt();

563

break;

564

}

565

}

566

}

567

568

if (lastException != null) {

569

throw new RuntimeException("Request failed after " + maxRetries + " retries", lastException);

570

}

571

572

return response;

573

}

574

}

575

```

576

577

## Types

578

579

```java { .api }

580

// Main filter interfaces

581

interface Filter {

582

Response filter(FilterableRequestSpecification requestSpec,

583

FilterableResponseSpecification responseSpec,

584

FilterContext ctx);

585

}

586

587

interface OrderedFilter extends Filter {

588

int getOrder();

589

}

590

591

interface FilterContext {

592

Response next(FilterableRequestSpecification requestSpec,

593

FilterableResponseSpecification responseSpec);

594

}

595

596

// Filterable specification interfaces

597

interface FilterableRequestSpecification extends RequestSpecification {

598

// Extends RequestSpecification with additional methods visible to filters

599

}

600

601

interface FilterableResponseSpecification extends ResponseSpecification {

602

// Extends ResponseSpecification with additional methods visible to filters

603

}

604

605

// Built-in filter classes

606

class RequestLoggingFilter implements Filter {

607

// Request logging implementation

608

}

609

610

class ResponseLoggingFilter implements Filter {

611

// Response logging implementation

612

}

613

614

class ErrorLoggingFilter implements Filter {

615

// Error logging implementation

616

}

617

618

class SessionFilter implements Filter {

619

// Session management implementation

620

}

621

622

class CookieFilter implements Filter {

623

// Cookie management implementation

624

}

625

626

class TimingFilter implements Filter {

627

// Timing measurement implementation

628

}

629

630

// Log detail enumeration

631

enum LogDetail {

632

ALL, STATUS, HEADERS, COOKIES, BODY, PARAMS, METHOD, URI

633

}

634

```

635

636

**Complete Filter Usage Example:**

637

638

```java

639

public class APITestWithFilters {

640

private static final String API_TOKEN = "your-api-token";

641

642

@Test

643

public void testWithMultipleFilters() {

644

// Setup global filters

645

RestAssured.filters(

646

new AuthorizationFilter(API_TOKEN),

647

new RequestIdFilter(),

648

ResponseLoggingFilter.logResponseIfStatusCodeIs(500)

649

);

650

651

// Create session filter for this test

652

SessionFilter sessionFilter = new SessionFilter();

653

654

// Test with additional request-specific filters

655

given()

656

.filter(sessionFilter)

657

.filter(new TimingFilter())

658

.contentType(ContentType.JSON)

659

.body(new User("John", "john@example.com"))

660

.when()

661

.post("/users")

662

.then()

663

.statusCode(201)

664

.time(lessThan(3L), TimeUnit.SECONDS)

665

.body("name", equalTo("John"));

666

667

// Use session filter for authenticated request

668

given()

669

.filter(sessionFilter)

670

.when()

671

.get("/users/me")

672

.then()

673

.statusCode(200);

674

}

675

}

676

```