Check Every Response Against OpenAPI With a REST Assured Filter
Check every response against an OpenAPI 3.1 description with a REST Assured filter, covering documented operations, statuses and content types, body schemas with $ref, and the difference between contract tests and functional tests.
Your payment API publishes an OpenAPI description that lists every path, method, status and body schema. Your tests copy parts of it into body(matchesJsonSchema(..)) checks, one test at a time, and the newest test forgets its check. Meanwhile a mobile app starts relying on GET /domestic-payments, an operation the contract never promised. In this guide, you’ll put a contract filter in the request specification, so every response is checked against the OpenAPI description automatically, and the tests themselves check only behaviour.
Level: Intermediate · Time: 25 minutes · Part of: Module 6: Schema and Contract Validation, section 4
What You’ll Build
You’ll build a test class called OpenApiContractTest with four tests, using the module’s OpenApiContractFilter. Two run normal flows and documented errors through the filter; two prove the filter fails a body that breaks the contract and an operation that isn’t documented.
The tests contain no schema checks. When a response breaks the contract, the filter fails the request itself:
1
2
3
4
GET /domestic-payments/{paymentId} 200 body
Expected: The content to match the given JSON schema.
$.status: does not have a value in the enumeration ["RCVD", "PDNG", "ACSP", "ACSC", "RJCT"]
...
When you’re done, Maven reports four passing tests:
1
2
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- Put the contract filter in a specification.
- Run normal flows through the filter.
- Let documented errors through.
- Catch a broken contract.
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 validate JSON against a schema, as taught in Validate Responses Against a JSON Schema in REST Assured and Test an RFC 9457 Error Contract in REST Assured, and build a request specification, from Build Reusable Request Specifications in REST Assured. No earlier OpenAPI knowledge is needed.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: create
OpenApiContractTestin a newsection_04package next to the classes from the previous sections, and follow every heading below. The filter is already in the module’ssupportpackage. - Skip ahead: open the finished class (
OpenApiContractTest.java) and the filter (OpenApiContractFilter.java) and read along. You can run them 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 Validate Responses Against a JSON Schema in REST Assured.
Out of scope: this guide doesn’t cover writing filters in general, or checking requests against the contract; filters are taught in Module 8.
Understand Contract Filters
The problem. Most APIs already have a complete contract: their OpenAPI description. Writing a schema check in each test duplicates it, the copies drift, and a test that forgets its check checks nothing. And no per-test schema check notices when a client relies on an operation or a status the contract never promised.
The concept. A REST Assured Filter runs around every request it’s added to: it can change the request, look at the response, or fail the test. A contract filter checks each response in three steps:
- The operation: the request’s method and path must be in the OpenAPI description.
- The status: the response status must be documented for that operation, or a
defaultresponse must exist. - The body: the response content type must be documented for that status, and the body must match its schema.
OpenAPI 3.1 schemas are JSON Schema 2020-12, so the filter validates bodies with the same matchesJsonSchema(..) as the earlier sections.
When to use it. Put the filter in the specification every test uses, so contract checks come for free, and keep the functional checks in the tests. The two kinds of test answer different questions:
| Contract test | Functional test | |
|---|---|---|
| Question | Does the API keep its promises? | Does it do the right thing? |
| Checks | Operations, statuses, content types, shapes | Values, state changes, business rules |
| Example | The payment has every required field | The amount of the payment is the amount sent |
A response can match its schema and still hold the wrong amount, and a correct amount can arrive in the wrong shape. A good suite has both.
Let the filter check the contract on every response, and let the tests check behaviour.
Meet the API Under Test
The tests use the payment initiation API from the earlier sections. Its OpenAPI 3.1 description, payment-initiation.openapi.json, has the server URL /pisp/v1 and documents two operations:
| Operation | Documented responses |
|---|---|
POST /domestic-payments | 201, 400, 415, 422 |
GET /domestic-payments/{paymentId} | 200, 404 |
The schemas live under components/schemas: PaymentRequest, Payment, Party, Amount and Problem. Responses refer to them with $ref, as in this excerpt:
1
2
3
4
5
6
7
8
9
10
11
12
13
"/domestic-payments/{paymentId}": {
"get": {
"operationId": "getDomesticPayment",
"parameters": [{ "name": "paymentId", "in": "path", "required": true, "schema": { "type": "string" } }],
"responses": {
"200": {
"description": "OK",
"content": { "application/json": { "schema": { "$ref": "#/components/schemas/Payment" } } }
},
"404": { "$ref": "#/components/responses/Problem" }
}
}
}
The API does more than the contract documents. GET /domestic-payments, which would list payments, and POST /payment-files, which takes the XML files from the previous section, aren’t in the description. And ?format=v0 returns the old payment shape from Validate Responses Against a JSON Schema in REST Assured.
Put the Contract Filter in a Specification
Read the Contract Filter
Goal: see how the filter checks each response, before you use it.
The module’s filter sends the request first, then checks what came back. Its filter(..) method looks like this, shortened:
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
@Override
public Response filter(FilterableRequestSpecification request, FilterableResponseSpecification responseSpec,
FilterContext context) {
Response response = context.next(request, responseSpec);
String method = request.getMethod().toLowerCase(Locale.ROOT);
String path = URI.create(request.getURI()).getPath();
if (!path.startsWith(serverPath)) {
throw new AssertionError(path + " is outside the server URL " + serverPath + " of the OpenAPI description");
}
String apiPath = path.substring(serverPath.length());
String template = findTemplate(apiPath);
Map<String, Object> operation = map(map(map(document.get("paths")).get(template)).get(method));
if (operation.isEmpty()) {
throw new AssertionError(method.toUpperCase(Locale.ROOT) + " " + template + " is not in the OpenAPI description");
}
Map<String, Object> responses = map(operation.get("responses"));
Object documented = responses.getOrDefault(String.valueOf(response.statusCode()), responses.get("default"));
if (documented == null) {
throw new AssertionError("Status " + response.statusCode() + " is not documented for "
+ method.toUpperCase(Locale.ROOT) + " " + template + "; documented: " + responses.keySet());
}
...
Map<String, Object> schema = new LinkedHashMap<>(map(media.get("schema")));
schema.put("$schema", "https://json-schema.org/draft/2020-12/schema");
schema.put("components", document.get("components"));
assertThat(method.toUpperCase(Locale.ROOT) + " " + template + " " + response.statusCode() + " body",
response.asString(), matchesJsonSchema(MAPPER.writeValueAsString(schema)));
return response;
}
What’s happening:
context.next(..)sends the request and returns the response. Everything after it is a check.- The
serverPathcheck makes sure the request went under/pisp/v1before that prefix is cut off, andfindTemplate(..)matches the real path, such as/domestic-payments/pmt-1, to a template, such as/domestic-payments/{paymentId}. - A
$refsuch as#/components/responses/Problemis followed in the part left out here. - Copying
componentsinto the validated schema keeps references such as#/components/schemas/Partyworking: they point into the same document. - The reason passed to
assertThat(..), such asGET /domestic-payments/{paymentId} 200 body, starts the failure message, so you know which operation broke its contract.
Checkpoint: there’s nothing to run yet. The filter is already in the module, and you’ll use it in the next step.
This is a teaching version that handles the parts of OpenAPI this module uses. For real projects,
com.atlassian.oai:openapi-request-validator-restassured, formerlyswagger-request-validator-restassured, is a complete filter of this kind that also checks requests. Check that the version you choose supports REST Assured 6.
Add the Filter to the Specification
Goal: create the test class with a specification that sends every request through the filter.
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
package com.javanibble.module_06.section_04;
import static com.javanibble.module_06.support.SamplePayments.domesticPayment;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertThrows;
import com.javanibble.module_06.support.OpenApiContractFilter;
import com.javanibble.pisp.PaymentInitiationApi;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class OpenApiContractTest {
private static PaymentInitiationApi api;
private static RequestSpecification pisp;
@BeforeAll
static void startApi() {
api = PaymentInitiationApi.start();
pisp = new RequestSpecBuilder()
.setBaseUri(api.baseUri()).setPort(api.port()).setBasePath(PaymentInitiationApi.BASE_PATH)
.addFilter(OpenApiContractFilter.fromClasspath("openapi/payment-initiation.openapi.json"))
.build();
}
@AfterAll
static void stopApi() {
api.close();
}
}
What’s happening:
OpenApiContractFilter.fromClasspath(..)loads the OpenAPI description fromsrc/test/resources.addFilter(..)puts the filter in the specification, so every request sent withgiven(pisp)passes through it.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Run Normal Flows Through the Filter
Create and Read a Payment
Goal: check behaviour only, and let the filter check both responses against the contract.
1
2
3
4
5
6
7
8
9
10
@Test
void initiateAndReadAPayment() {
String id = given(pisp)
.contentType(ContentType.JSON).body(domesticPayment("INV-10", "99.95"))
.when().post("/domestic-payments")
.then().statusCode(201)
.extract().path("paymentId");
given(pisp).when().get("/domestic-payments/{id}", id).then().statusCode(200);
}
What’s happening:
- The test checks only that the payment can be created and read back.
- It contains no schema check, yet the filter validated both responses against the
Paymentschema.
Checkpoint: run OpenApiContractTest from your IDE. One test runs and passes.
Let Documented Errors Through
Trigger a 404 and a 422
Goal: prove that errors the contract documents pass the filter, as long as their bodies match.
1
2
3
4
5
@Test
void documentedErrorsPassToo() {
given(pisp).when().get("/domestic-payments/{id}", "pmt-404").then().statusCode(404);
given(pisp).contentType(ContentType.JSON).body("{}").when().post("/domestic-payments").then().statusCode(422);
}
What’s happening:
- A
404forGETand a422forPOSTare both documented, through#/components/responses/Problem. - So the filter checks their bodies against the
Problemschema and lets them through.
Checkpoint: run the class again. Two tests pass.
Catch a Broken Contract
Read a Body That Breaks the Contract
Goal: prove that the filter fails a response whose body doesn’t match its schema, without any then().
1
2
3
4
5
6
7
8
9
10
11
12
@Test
void aBodyThatBreaksTheContractFailsTheTest() {
String id = given(pisp)
.contentType(ContentType.JSON).body(domesticPayment("INV-11", "1.00"))
.when().post("/domestic-payments")
.then().extract().path("paymentId");
AssertionError error = assertThrows(AssertionError.class, () ->
given(pisp).queryParam("format", "v0").when().get("/domestic-payments/{id}", id));
assertThat(error.getMessage(), containsString("GET /domestic-payments/{paymentId} 200 body"));
}
What’s happening:
?format=v0returns the old payment shape with a documented status,200.- The filter runs while the request is sent, so
get(..)itself throws; the request has nothen()at all. - The message starts with the operation and status, then lists every problem:
1
2
3
4
5
6
GET /domestic-payments/{paymentId} 200 body
Expected: The content to match the given JSON schema.
$.status: does not have a value in the enumeration ["RCVD", "PDNG", "ACSP", "ACSC", "RJCT"]
$.amount: number found, object expected
$: required property 'instructionId' not found
...
Checkpoint: run the class again. Three tests pass.
Expect the failure on the request, not in
then(). The filter fails insideget(..)orpost(..), so wrap the request itself inassertThrows(..), as this test does.
Call an Undocumented Operation
Goal: prove that the filter fails a request to an operation the contract doesn’t have.
1
2
3
4
5
6
7
@Test
void anUndocumentedOperationFailsTheTest() {
AssertionError error = assertThrows(AssertionError.class, () ->
given(pisp).when().get("/domestic-payments"));
assertThat(error.getMessage(), containsString("GET /domestic-payments is not in the OpenAPI description"));
}
What’s happening:
- The path
/domestic-paymentsexists in the description, but only forPOST. - Whatever the API answers, a client that relies on
GET /domestic-paymentsrelies on something the contract never promised. The filter turns that into a failing test.
Checkpoint: run the class again. All four tests pass.
Add the filter only to specifications for documented endpoints, or document them.
POST /payment-filesisn’t in this description, so the filter fails it with/payment-files is not a path in the OpenAPI description, even though the API handles it.
Run the Tests
Run the following command from the repository root:
1
mvn test -pl module-06 -Dtest=OpenApiContractTest
You should see a result similar to the following:
1
2
3
4
5
6
[INFO] Running com.javanibble.module_06.section_04.OpenApiContractTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.508 s -- in com.javanibble.module_06.section_04.OpenApiContractTest
[INFO]
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Make a Test Fail
In src/test/resources/openapi/payment-initiation.openapi.json, delete the "404" response of GET /domestic-payments/{paymentId}, and the comma before it, and run the command again. You should see a result similar to the following:
1
2
[ERROR] Failures:
[ERROR] OpenApiContractTest.documentedErrorsPassToo:60 Status 404 is not documented for GET /domestic-payments/{paymentId}; documented: [200]
The API still answers 404 for an unknown payment, but the contract no longer promises it, so the filter fails the request and lists the statuses that are documented. The test itself didn’t change: a change to the contract alone turned it red, which is what keeps the description and the API in step.
Put the "404" response back and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
GET /domestic-payments is not in the OpenAPI description | The path exists, but not for this method | Document the operation, or don’t call it |
/payment-files is not a path in the OpenAPI description | The path isn’t in the description at all | Use a specification without the filter, or document the path |
Status 404 is not documented for ...; documented: [200] | The response status isn’t in the operation’s responses | Document the status, or add a default response |
GET /domestic-payments/{paymentId} 200 body followed by schema errors | The body doesn’t match the documented schema | Fix the response, or update the schema if the change is intended |
Try It Yourself
Exercise 1: Send Two More Documented Errors
The contract documents 400 and 415 for POST /domestic-payments. Add a test called malformedJsonAndTheWrongContentTypeAreDocumented that sends a body that isn’t JSON and a text/plain body through the filter, and checks the statuses 400 and 415.
Hint
Start from documentedErrorsPassToo. The filter checks the problem bodies, so the test only needs the statuses.
Solution
1
2
3
4
5
@Test
void malformedJsonAndTheWrongContentTypeAreDocumented() {
given(pisp).contentType(ContentType.JSON).body("{ not json").when().post("/domestic-payments").then().statusCode(400);
given(pisp).contentType(ContentType.TEXT).body("hello").when().post("/domestic-payments").then().statusCode(415);
}
Exercise 2: Combine a Contract Test With a Functional Test
Add a test called aPaymentReadBackHoldsWhatWasSent. Create a payment with the instruction id "INV-12" and the amount "42.50", then read it back. Let the filter check the contract, and check in the test that the payment holds the instruction id and amount that were sent, and that its status is "RCVD".
Hint
Start from initiateAndReadAPayment. The body(..) checks you add are the functional part: values the schema can’t know.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
void aPaymentReadBackHoldsWhatWasSent() {
String id = given(pisp)
.contentType(ContentType.JSON).body(domesticPayment("INV-12", "42.50"))
.when().post("/domestic-payments")
.then().statusCode(201)
.extract().path("paymentId");
given(pisp)
.when()
.get("/domestic-payments/{id}", id)
.then()
.statusCode(200)
.body("instructionId", equalTo("INV-12"))
.body("amount.value", equalTo("42.50"))
.body("status", equalTo("RCVD"));
}
Add import static org.hamcrest.Matchers.equalTo; to the class.
Summary
You built OpenApiContractTest, which sends every request through a contract filter, runs normal flows and documented errors with no schema checks in the tests, and proves the filter fails a broken body and an undocumented operation. No test can forget its contract check any more, and a client can’t rely on an undocumented operation unnoticed.
- A contract filter checks every response against the API’s OpenAPI description: the operation must exist, the status must be documented, and the body must match its schema.
- OpenAPI 3.1 schemas are JSON Schema 2020-12, so
matchesJsonSchema(..)does the body check, and copyingcomponentskeeps$refs working. - Put the filter in a request specification, and every test gets contract checks for free.
- The filter fails inside
get(..)orpost(..), so test for its failures withassertThrows(..)around the request. - A contract test asks whether the API keeps its promises, a functional test whether it does the right thing; keep both. For real projects, use a complete filter such as Atlassian’s
openapi-request-validator-restassured.
Here are the commands you used in this guide:
1
mvn test -pl module-06 -Dtest=OpenApiContractTest
What’s Next
Next: you’ve completed Module 6. Continue with Module 7: Authentication and Transport Security, starting with Test HTTP Basic Authentication in REST Assured, which tests the 401 challenge and challenged and preemptive Basic.
The code:
- The finished test class:
OpenApiContractTest.java - The filter:
OpenApiContractFilter.java - The contract:
payment-initiation.openapi.json - The code and run commands for this module: Module 6 README
Go deeper:
- OpenAPI Specification 3.1, for paths, responses and components.
- swagger-request-validator, Atlassian’s complete validator, with a REST Assured module.
Related guides:
- Test an RFC 9457 Error Contract in REST Assured, for the problem schema the filter checks errors against.
- Module 8: Filters and Extensibility, for writing your own filters.
