Post

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.

Check Every Response Against OpenAPI With a REST Assured Filter

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

How to Complete This Guide

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

  • Build it step by step: create OpenApiContractTest in a new section_04 package next to the classes from the previous sections, and follow every heading below. The filter is already in the module’s support package.
  • 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 default response 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 testFunctional test
QuestionDoes the API keep its promises?Does it do the right thing?
ChecksOperations, statuses, content types, shapesValues, state changes, business rules
ExampleThe payment has every required fieldThe 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:

OperationDocumented responses
POST /domestic-payments201, 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 serverPath check makes sure the request went under /pisp/v1 before that prefix is cut off, and findTemplate(..) matches the real path, such as /domestic-payments/pmt-1, to a template, such as /domestic-payments/{paymentId}.
  • A $ref such as #/components/responses/Problem is followed in the part left out here.
  • Copying components into the validated schema keeps references such as #/components/schemas/Party working: they point into the same document.
  • The reason passed to assertThat(..), such as GET /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, formerly swagger-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 from src/test/resources.
  • addFilter(..) puts the filter in the specification, so every request sent with given(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 Payment schema.

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 404 for GET and a 422 for POST are both documented, through #/components/responses/Problem.
  • So the filter checks their bodies against the Problem schema 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=v0 returns the old payment shape with a documented status, 200.
  • The filter runs while the request is sent, so get(..) itself throws; the request has no then() 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 inside get(..) or post(..), so wrap the request itself in assertThrows(..), 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-payments exists in the description, but only for POST.
  • Whatever the API answers, a client that relies on GET /domestic-payments relies 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-files isn’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

SymptomLikely causeFix
GET /domestic-payments is not in the OpenAPI descriptionThe path exists, but not for this methodDocument the operation, or don’t call it
/payment-files is not a path in the OpenAPI descriptionThe path isn’t in the description at allUse 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 responsesDocument the status, or add a default response
GET /domestic-payments/{paymentId} 200 body followed by schema errorsThe body doesn’t match the documented schemaFix 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 copying components keeps $refs working.
  • Put the filter in a request specification, and every test gets contract checks for free.
  • The filter fails inside get(..) or post(..), so test for its failures with assertThrows(..) 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:

Go deeper:

Related guides:

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