Post

Build Reusable Request Specifications in REST Assured

Build a RequestSpecification once and reuse it, layer one specification on another, test without credentials, override a header with HeaderConfig, replace the base path, and inspect a specification with SpecificationQuerier.

Build Reusable Request Specifications in REST Assured

Every request to your open banking API needs the same base URI, port, base path, bearer token and Accept header. Your suite copies those lines into fifty tests, and when the test token changes, you edit fifty tests. Static defaults on RestAssured would remove the copies, but they’re global state. In this guide, you’ll put the shared set-up in request specifications: small, immutable objects that every test builds on, and that a security test can leave out.

Level: Intermediate · Time: 20 minutes · Part of: Module 5: Reusable Specifications and Configuration, section 1

What You’ll Build

You’ll build a test class called RequestSpecificationTest with six tests. It builds two layered specifications, one with credentials and one without, uses them in requests, overrides and replaces what they set, and inspects one.

Most tests send this request and check this response:

1
2
3
4
5
6
7
8
9
10
GET /open-banking/v4.0/aisp/accounts HTTP/1.1
Host: localhost:<port>
Accept: application/json, application/javascript, text/javascript, text/json
Authorization: Bearer test-token
x-fapi-interaction-id: 5b83ad6c-90b7-49bb-814a-796b93a9e07b

HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8

{"Data":{"Account":[{"AccountId":"22289", ...}, ...]},"Links":{...},"Meta":{"TotalPages":1}}

When you’re done, Maven reports six passing tests:

1
2
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

In this guide, you will:

  • Build and layer specifications.
  • Use a specification in a request.
  • Change what a specification set.
  • Inspect a specification.

What You Need

How to Complete This Guide

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

  • Build it step by step: this is the first section of Module 5, so you start from scratch. Create RequestSpecificationTest in the module-05 test sources and follow every heading below.
  • Skip ahead: open the finished class (RequestSpecificationTest.java) and read along. You can run it at any time with the command in Run the Tests.

Get the code: clone the examples repository and change into it:

1
2
git clone https://github.com/javanibble/rest-assured-examples.git
cd rest-assured-examples

If you’ve already cloned it for an earlier module, run git pull instead.

Out of scope: this guide doesn’t cover response specifications, client configuration such as timeouts, or masking secrets in logs; they’re taught in section 2, section 3 and section 4.

Understand Request Specifications

The problem. The set-up every request to an API shares, such as where it is and how to authenticate, gets copied into every test. Copies drift and multiply edits. Static defaults such as RestAssured.baseURI remove the copies, but they apply to the whole JVM, need resetting, and break when two test classes run in parallel.

The concept. A RequestSpecification holds everything a request can carry: base URI, port, base path, headers, parameters, cookies, body, config and filters. You’ve used one all along: given() returns one. A specification built with RequestSpecBuilder differs in two ways:

  • It’s built once and reused. Each set.. or add.. call adds a setting, and build() returns the finished, immutable specification.
  • It can’t send requests itself. You merge it into a new request with given(spec) or given().spec(spec), and that request sends.

Specifications can be layered: addRequestSpecification(other) starts a builder from another specification. When a request sets something its specification already has, headers are merged, and values that can have only one value, such as the base path, are replaced.

When to use it. Put what every request to an API shares in a specification, and layer small specifications with clear purposes, such as “where the API is” and “plus credentials”. Keep values that must be new for every request, such as an interaction id, an idempotency key or a nonce, in the test.

Build the shared set-up once, in small layers, and add only what’s special in each test.

Meet the API Under Test

Module 5 tests an account information API in the style of the UK Open Banking (OBIE) standard. It runs on the JDK’s built-in HTTP server, like the APIs of the earlier modules, starts on a free port, and serves its endpoints under /open-banking/v4.0/aisp. Every request must follow three rules:

RuleWithout it
Authorization: Bearer test-token401, A valid bearer token is required, with WWW-Authenticate: Bearer realm="aisp"
An x-fapi-interaction-id header, echoed in the response400, The header x-fapi-interaction-id is required
An Accept header that allows JSON406, This API only produces application/json

Bodies use OBIE’s envelope, with capitalised Data, Links and Meta. GET /accounts/22289 returns:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
    "Data": {
        "Account": [
            {
                "AccountId": "22289",
                "Currency": "EUR",
                "AccountType": "Personal",
                "AccountSubType": "CurrentAccount",
                "Nickname": "Main account",
                "Account": [{ "SchemeName": "UK.OBIE.IBAN", "Identification": "NL91ABNA0417164300" }]
            }
        ]
    },
    "Links": { "Self": "/open-banking/v4.0/aisp/accounts/22289" },
    "Meta": { "TotalPages": 1 }
}

There are three accounts: 22289 (Main account) and 31820 (Holiday fund), both personal, and 40114 (Bakery), a business account. Under /test-support, without any of the three rules, GET /landing answers {"method":"GET"}.

Your tests check these values:

  • Data.Account, the list of accounts, and Data.Account[0].Nickname.
  • The 401 and its WWW-Authenticate header, for a request without credentials.
  • The method echoed by /test-support/landing, for a request whose base path was replaced.

Build and Layer Specifications

Build a Specification and One on Top of It

Goal: create the test class, and build a specification for the server and one that adds credentials.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.javanibble.module_05.section_01;

import static io.restassured.RestAssured.given;
import static io.restassured.config.HeaderConfig.headerConfig;
import static io.restassured.config.RestAssuredConfig.config;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;

import com.javanibble.openbanking.OpenBankingApi;

import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.QueryableRequestSpecification;
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.SpecificationQuerier;

import java.util.UUID;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

class RequestSpecificationTest {

    private static OpenBankingApi api;
    private static RequestSpecification server;
    private static RequestSpecification authenticated;

    @BeforeAll
    static void startApiAndBuildSpecifications() {
        api = OpenBankingApi.start();

        server = new RequestSpecBuilder()
                .setBaseUri(api.baseUri())
                .setPort(api.port())
                .setBasePath(OpenBankingApi.BASE_PATH)
                .setAccept(ContentType.JSON)
                .build();

        authenticated = new RequestSpecBuilder()
                .addRequestSpecification(server)
                .addHeader("Authorization", "Bearer test-token")
                .build();
    }

    @AfterAll
    static void stopApi() {
        api.close();
    }

    private static String interactionId() {
        return UUID.randomUUID().toString();
    }
}

What’s happening:

  • server says where the API is, and that the client accepts JSON.
  • authenticated starts from server with addRequestSpecification(..), and adds the token.
  • Both are built once in @BeforeAll and kept in fields. They’re ordinary objects, so another test class can build different ones, even in parallel.
  • interactionId() returns a random UUID, because the interaction id must be new for every request.

Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.

Don’t put per-request values in a shared specification. An interaction id, an idempotency key or a nonce must be new for every request, so add them in the test, as these tests do with interactionId().

Use a Specification in a Request

Pass It to given(..)

Goal: list the accounts with the authenticated specification.

1
2
3
4
5
6
7
8
9
10
@Test
void givenTakesASpecification() {
    given(authenticated)
        .header("x-fapi-interaction-id", interactionId())
    .when()
        .get("/accounts")
    .then()
        .statusCode(200)
        .body("Data.Account", hasSize(3));
}

What’s happening:

  • given(authenticated) starts a request from the specification: base URI, port, base path, Accept and token.
  • The test adds only what’s special about it: a new interaction id.

Checkpoint: run RequestSpecificationTest from your IDE. One test runs and passes.

Add It With spec(..)

Goal: read one account, adding the specification with spec(..).

1
2
3
4
5
6
7
8
9
10
11
@Test
void orAddItWithSpec() {
    given()
        .spec(authenticated)
        .header("x-fapi-interaction-id", interactionId())
    .when()
        .get("/accounts/{id}", "22289")
    .then()
        .statusCode(200)
        .body("Data.Account[0].Nickname", equalTo("Main account"));
}

What’s happening:

  • given().spec(authenticated) does the same as given(authenticated). Use whichever reads better.

Checkpoint: run the class again. Two tests pass.

A built specification can’t send a request itself. Since REST Assured 6.2, authenticated.get("/accounts") throws IllegalStateException: A request specification built by RequestSpecBuilder can't send a request or hold response expectations itself. Always go through given(spec) or given().spec(spec).

Send Without Credentials

Goal: prove that a request without the token is rejected.

1
2
3
4
5
6
7
8
9
10
@Test
void theSpecificationWithoutCredentialsIsRejected() {
    given(server)
        .header("x-fapi-interaction-id", interactionId())
    .when()
        .get("/accounts")
    .then()
        .statusCode(401)
        .header("WWW-Authenticate", "Bearer realm=\"aisp\"");
}

What’s happening:

  • server is the layer below authenticated, so it has everything except the token.
  • Because the token lives in its own layer, this negative test needs no special set-up.
  • WWW-Authenticate tells the client which scheme the API expects.

Checkpoint: run the class again. Three tests pass.

Change What a Specification Set

Override a Header

Goal: replace the specification’s token with a revoked one, and prove that the API rejects it.

1
2
3
4
5
6
7
8
9
10
11
@Test
void overridingAHeaderOfTheSpecification() {
    given(authenticated)
        .config(config().headerConfig(headerConfig().overwriteHeadersWithName("Authorization")))
        .header("Authorization", "Bearer revoked-token")
        .header("x-fapi-interaction-id", interactionId())
    .when()
        .get("/accounts")
    .then()
        .statusCode(401);
}

What’s happening:

  • Headers merge, so without configuration a second Authorization header would be sent next to the specification’s one.
  • overwriteHeadersWithName("Authorization") makes the test’s value replace the specification’s.
  • Now only the revoked token reaches the API, and it answers 401.

Checkpoint: run the class again. Four tests pass.

Without HeaderConfig, the override fails silently. The request log shows both headers, Authorization=Bearer test-token and Authorization=Bearer revoked-token; the API reads the first, valid one and answers 200. A test that expects 401 fails, and worse, a test that expects 200 passes for the wrong reason.

Replace the Base Path

Goal: show that a value other than a header is replaced, not merged.

1
2
3
4
5
6
7
8
9
10
@Test
void valuesOtherThanHeadersAreReplaced() {
    given(authenticated)
        .basePath("/test-support")
    .when()
        .get("/landing")
    .then()
        .statusCode(200)
        .body("method", equalTo("GET"));
}

What’s happening:

  • basePath("/test-support") replaces the specification’s base path for this request only.
  • The request goes to /test-support/landing, with the specification’s base URI and port.
  • The specification itself doesn’t change: it’s immutable, so the next test that uses it gets the original base path.

Checkpoint: run the class again. Five tests pass.

Inspect a Specification

Query a Specification’s Settings

Goal: read back the base path, port and token a layered specification ends up with.

1
2
3
4
5
6
7
8
@Test
void aSpecificationCanBeInspected() {
    QueryableRequestSpecification query = SpecificationQuerier.query(authenticated);

    assertEquals(OpenBankingApi.BASE_PATH, query.getBasePath());
    assertEquals(api.port(), query.getPort());
    assertEquals("Bearer test-token", query.getHeaders().getValue("Authorization"));
}

What’s happening:

  • SpecificationQuerier.query(..) returns a read-only view of a specification.
  • authenticated reports the base path and port it inherited from server, and its own token.
  • This is useful in a test of the code that builds your specifications, or to debug what a layered specification ends up with. No request is sent.

Checkpoint: run the class again. All six tests pass.

RestAssured.requestSpecification = spec also works, but it’s the same global state as RestAssured.baseURI. Keep specifications in fields, or pass them in, and they need none of the resetting that static defaults do.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-05 -Dtest=RequestSpecificationTest

You should see a result similar to the following:

1
2
3
4
5
6
[INFO] Running com.javanibble.module_05.section_01.RequestSpecificationTest
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.419 s -- in com.javanibble.module_05.section_01.RequestSpecificationTest
[INFO]
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Make a Test Fail

In overridingAHeaderOfTheSpecification, delete the .config(config().headerConfig(..)) line and run the command again. You should see a result similar to the following:

1
2
3
[ERROR] Failures:
[ERROR]   RequestSpecificationTest.overridingAHeaderOfTheSpecification:110 1 expectation failed.
Expected status code <401> but was <200>.

The revoked token was sent, but so was the specification’s valid one, and the API used the valid one. Add .log().headers() before when() to see both Authorization headers in the log. This is the silent failure from the danger callout, caught because the test expected a refusal.

Put the .config(..) line back and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
IllegalStateException: A request specification built by RequestSpecBuilder can't send a request ...The test sent the request from a built specificationUse given(spec) or given().spec(spec)
An overridden header has no effectHeaders merge, so both values were sentAdd headerConfig().overwriteHeadersWithName(..)
401 with A valid bearer token is requiredThe request used a specification without credentialsUse the authenticated specification
400 with The header x-fapi-interaction-id is requiredThe test didn’t add an interaction idAdd header("x-fapi-interaction-id", interactionId())
406 with This API only produces application/jsonThe request’s Accept header doesn’t allow JSONKeep the specification’s setAccept(ContentType.JSON)

Try It Yourself

Exercise 1: Read the Business Account

Add a test called theBusinessAccount that reads account 40114 with the authenticated specification, and checks that its AccountType is "Business" and that its Links.Self ends with /accounts/40114.

Hint

Start from orAddItWithSpec. Remember the interaction id, and use endsWith(..) from Hamcrest for the link.

Solution
1
2
3
4
5
6
7
8
9
10
11
@Test
void theBusinessAccount() {
    given(authenticated)
        .header("x-fapi-interaction-id", interactionId())
    .when()
        .get("/accounts/{id}", "40114")
    .then()
        .statusCode(200)
        .body("Data.Account[0].AccountType", equalTo("Business"))
        .body("Links.Self", endsWith("/accounts/40114"));
}

Add import static org.hamcrest.Matchers.endsWith; to the class.

Exercise 2: Test the API’s Other Rules

Add a test called theApiEnforcesItsOtherRules that checks, with the authenticated specification: a request without an interaction id gets 400; a request whose Accept is text/plain gets 406; and a request with an interaction id gets 200 and the same id back in the x-fapi-interaction-id response header. Finish by checking with SpecificationQuerier that the server specification has no Authorization header.

Hint

accept(..) overwrites the specification’s Accept without any configuration, because Accept is one of the headers that’s overwritten by default. Keep the interaction id in a variable so you can compare it with the response header. getValue(..) returns null for a missing header.

Solution
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
@Test
void theApiEnforcesItsOtherRules() {
    given(authenticated)
    .when()
        .get("/accounts")
    .then()
        .statusCode(400);

    given(authenticated)
        .accept("text/plain")
        .header("x-fapi-interaction-id", interactionId())
    .when()
        .get("/accounts")
    .then()
        .statusCode(406);

    String interaction = interactionId();
    given(authenticated)
        .header("x-fapi-interaction-id", interaction)
    .when()
        .get("/accounts")
    .then()
        .statusCode(200)
        .header("x-fapi-interaction-id", interaction);

    assertNull(SpecificationQuerier.query(server).getHeaders().getValue("Authorization"));
}

Add import static org.junit.jupiter.api.Assertions.assertNull; to the class.

Summary

You built RequestSpecificationTest, which builds a specification for the server and one with credentials on top of it, uses them in requests, overrides a header, replaces the base path, and inspects a specification. A token change is now one edit, not fifty.

  • A RequestSpecification built with RequestSpecBuilder holds the set-up every request to an API shares, and is immutable.
  • Use it with given(spec) or given().spec(spec); a built specification can’t send a request itself.
  • Layer small specifications with addRequestSpecification(..), so a security test can use the layer without credentials.
  • When a request sets what its specification has, headers are merged and other values, such as the base path, are replaced; use HeaderConfig.overwriteHeadersWithName(..) to replace a header.
  • SpecificationQuerier.query(..) shows what a specification holds, without sending a request.

Here are the commands you used in this guide:

1
2
3
git clone https://github.com/javanibble/rest-assured-examples.git
cd rest-assured-examples
mvn test -pl module-05 -Dtest=RequestSpecificationTest

What’s Next

Next: continue with Share Response Checks With Response Specifications in REST Assured, which shares the checks every response must pass, as this guide shared the set-up of every request.

The code:

Go deeper:

Related guides:

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