Chain Requests Into an API Flow in REST Assured
Build a flow of requests in which each step uses what the previous one returned, covering following a Location header, the open banking consent flow from customer to balances, and the negative cases of an unauthorised consent and a missing permission.
To read a customer’s balances, an open banking client creates a consent, has it authorised, reads the accounts it covers, and only then asks for a balance. Your test of that flow hard-codes consent-1 and builds the authorisation URL by hand, so it breaks when another test runs first, or when the API changes its URLs. And no test checks what a consent must refuse. In this guide, you’ll chain requests so each step uses what the previous one returned, follow the links the API gives you, and test the refusals as carefully as the happy path.
Level: Intermediate · Time: 25 minutes · Part of: Module 4: Extracting Values and Mapping Objects, section 5
What You’ll Build
You’ll build a test class called ChainingRequestsTest with four tests. One follows a Location header; one runs the whole consent flow from a new customer to a balance; two prove that a consent opens nothing it shouldn’t.
The full flow sends five requests, each using a value from the one before:
1
2
3
4
5
POST /api/v1/customers → 201, a customer id
POST /api/v1/consents → 201, a consent id and an "authorise" link
POST /api/v1/consents/consent-1/authorisation → 200, status AUTHORISED
GET /api/v1/accounts (Consent-ID) → 200, the customer's accounts
GET /api/v1/accounts/acc-1/balances (Consent-ID) → 200, the balances
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:
- Follow a Location header.
- Run the full consent flow.
- Test what a consent must refuse.
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 extract values after validating, as taught in Extract Values From a Response in REST Assured, map responses to records with a
TypeRef, from Map Responses to Java Records in REST Assured, and you know how a base path is applied, from Control Where REST Assured Requests Go.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: create
ChainingRequestsTestin a newsection_05package next to the classes from the previous sections, and follow every heading below. - Skip ahead: open the finished class (
ChainingRequestsTest.java) and read along. You can run it 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 Extract Values From a Response in REST Assured.
Out of scope: this guide doesn’t cover long multi-step workflows with idempotency, ETags or polling, or authentication; they’re taught in Module 9 and Module 7.
Understand Chains of Requests
The problem. Real API usage is rarely one request. Each step of a flow needs something from the step before: an id, a link, a header value. Hard-coding those values ties a test to the order tests run in, building URLs by hand duplicates what the API already knows, and a step that fails silently in the middle makes a later step fail with a confusing error.
The concept. A chain is a test in which each request uses a value from an earlier response. Three rules keep chains reliable:
- Validate every step before you use it. A failed step should fail the test at that step, with a clear message.
- Follow the links the API gives you. A
Locationheader or a_linksentry says where to go next; building the URL yourself breaks when the API changes it. - Create the data each test needs. Every test starts from its own customer or consent, so tests don’t depend on each other or on their order.
Each step follows the same pattern: send, validate, extract what the next step needs.
When to use it. Use a chain to test a flow a real client goes through, and to test what the flow must refuse. Map a response to a record when the next steps need several of its values; use extract().path(..) when they need one.
Send, validate, extract, and follow the links, at every step.
Meet the API Under Test
The Customers and Consents API is modelled on open banking account access consents (PSD2 AIS):
| Step | Request | Response |
|---|---|---|
| 1. Create a customer | POST /customers | 201 with Location |
| 2. Request a consent | POST /consents with customerId and permissions | 201, status AWAITING_AUTHORISATION, with _links |
| 3. Authorise it | POST to the authorise link | 200, status AUTHORISED |
| 4. Read accounts | GET /accounts, header Consent-ID | The accounts, if the consent has ReadAccountsBasic |
| 5. Read balances | GET /accounts/{id}/balances, header Consent-ID | The balances, if the consent has ReadBalances |
A new consent links to its own authorisation:
1
2
3
4
5
6
7
8
9
10
11
{
"consentId": "consent-1",
"customerId": "cust-1",
"permissions": ["ReadAccountsBasic", "ReadBalances"],
"status": "AWAITING_AUTHORISATION",
"expiresOn": "2027-02-19",
"_links": {
"self": { "href": "/api/v1/consents/consent-1" },
"authorise": { "href": "/api/v1/consents/consent-1/authorisation" }
}
}
The balances of an account look like this:
1
2
3
4
5
6
{
"accountId": "acc-1001",
"balances": [
{ "type": "closingBooked", "amount": { "amount": "15000.00", "currency": "EUR" } }
]
}
The Consent-ID header is the key, and the API refuses requests that don’t qualify:
| Request | Answer |
|---|---|
No Consent-ID header | 400, The header Consent-ID is required |
| A consent that isn’t authorised, or doesn’t exist | 403, Consent consent-N is not authorised |
Balances without ReadBalances | 403, Consent consent-N lacks the permission ReadBalances |
| An account the consent doesn’t cover | 404, Account acc-N is not covered by the consent |
Your tests use these values:
- The new customer’s
idandLocation, and the consent’sconsentIdandauthoriselink. - The
statusafter each consent step, and the first account’saccountId. - The
detailof each refusal, which proves why it was refused.
Follow a Location Header
Set Up the Test Class
Goal: create the test class, start the Consents API and add the shared request helper.
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
package com.javanibble.module_04.section_05;
import static io.restassured.RestAssured.given;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import com.javanibble.consents.ConsentsApi;
import com.javanibble.module_04.support.Models.Account;
import com.javanibble.module_04.support.Models.Consent;
import com.javanibble.module_04.support.Models.Customer;
import com.javanibble.module_04.support.Models.NewConsent;
import com.javanibble.module_04.support.Models.NewCustomer;
import io.restassured.common.mapper.TypeRef;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import java.util.List;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class ChainingRequestsTest {
private static ConsentsApi api;
@BeforeAll
static void startApi() {
api = ConsentsApi.start();
}
@AfterAll
static void stopApi() {
api.close();
}
private static RequestSpecification consentsApi() {
return given().baseUri(api.baseUri()).port(api.port()).basePath(ConsentsApi.BASE_PATH);
}
}
What’s happening:
consentsApi()sets the base path/api/v1, for the requests whose paths the tests write themselves.- The records come from the module’s
Modelsclass, as in the previous sections.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Create a Customer and Follow Its Location
Goal: create a customer, then read it back through the Location header the API returned.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
void createThenFollowTheLocationHeader() {
String location = consentsApi()
.contentType(ContentType.JSON)
.body(new NewCustomer("Lotte Laan", "lotte@example.nl", "RETAIL"))
.when()
.post("/customers")
.then()
.statusCode(201)
.extract().header("Location");
given().baseUri(api.baseUri()).port(api.port())
.when()
.get(location)
.then()
.statusCode(200)
.body("name", equalTo("Lotte Laan"));
}
What’s happening:
- The first request validates the
201before it extracts theLocation, such as/api/v1/customers/cust-6. - That path already starts with
/api/v1, so the second request is built withoutbasePath(..), and the path is used as it is. - The test never builds the customer’s URL; it uses the one the API gave it.
Checkpoint: run ChainingRequestsTest from your IDE. One test runs and passes.
Don’t send a
Locationthrough a request with a base path. With the usualconsentsApi()helper, REST Assured puts/api/v1in front of a path that already has it, so the request goes to/api/v1/api/v1/customers/cust-6and gets a404. You’ll see that failure in Make a Test Fail.
Run the Full Consent Flow
Go From Customer to Balances
Goal: create a customer, request and authorise a consent, read the accounts, and read a balance, with each step using what the previous one returned.
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
@Test
void theFullConsentFlow() {
Customer customer = consentsApi()
.contentType(ContentType.JSON)
.body(new NewCustomer("Daan Dekker", "daan@example.nl", "RETAIL"))
.when().post("/customers")
.then().statusCode(201)
.extract().as(Customer.class);
Consent consent = consentsApi()
.contentType(ContentType.JSON)
.body(new NewConsent(customer.id(), List.of("ReadAccountsBasic", "ReadBalances")))
.when().post("/consents")
.then().statusCode(201)
.body("status", equalTo("AWAITING_AUTHORISATION"))
.extract().as(Consent.class);
given().baseUri(api.baseUri()).port(api.port())
.when().post(consent.links().get("authorise").href())
.then().statusCode(200)
.body("status", equalTo("AUTHORISED"));
List<Account> accounts = consentsApi()
.header("Consent-ID", consent.consentId())
.when().get("/accounts")
.then().statusCode(200)
.extract().as(new TypeRef<List<Account>>() {});
assertThat(accounts).hasSize(2);
consentsApi()
.header("Consent-ID", consent.consentId())
.when()
.get("/accounts/{id}/balances", accounts.getFirst().accountId())
.then()
.statusCode(200)
.body("balances[0].type", equalTo("closingBooked"))
.body("balances[0].amount.currency", equalTo("EUR"));
}
What’s happening:
- The customer is mapped to a record, and its
idgoes into the consent request. - The consent is checked for its starting status, then mapped, so its id and links are available.
- The authorisation follows the
authoriselink. It’s an absolute path like theLocation, so the request has no base path. - The accounts are read with the consent id and mapped with a
TypeRef. A new retail customer has two accounts, current and savings. - The balances of the first account end the flow, with checks on nested values.
Checkpoint: run the class again. Two tests pass.
Follow the links the API gives you. The test doesn’t know the authorisation URL pattern, and doesn’t need to: if the API changes it, the
authoriselink changes with it, and the test keeps working.
Test What a Consent Must Refuse
A flow test proves that the happy path works. In a security-sensitive API, the tests that prove what’s refused matter as much.
Use an Unauthorised Consent
Goal: prove that a consent nobody authorised opens no accounts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
void aConsentThatIsNotAuthorisedOpensNothing() {
String consentId = consentsApi()
.contentType(ContentType.JSON)
.body(new NewConsent("cust-1", List.of("ReadAccountsBasic")))
.when().post("/consents")
.then().statusCode(201)
.extract().path("consentId");
consentsApi()
.header("Consent-ID", consentId)
.when()
.get("/accounts")
.then()
.statusCode(403)
.body("detail", containsString("not authorised"));
}
What’s happening:
- The consent exists, but the test never authorises it.
- The API answers
403with the detailConsent consent-N is not authorised. - Only one value from the first response is needed, so
extract().path(..)is enough; no record is required.
Checkpoint: run the class again. Three tests pass.
Use a Consent Without a Permission
Goal: prove that an authorised consent grants only the permissions it lists.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
void aConsentOnlyGrantsItsPermissions() {
Consent consent = consentsApi()
.contentType(ContentType.JSON)
.body(new NewConsent("cust-1", List.of("ReadAccountsBasic")))
.when().post("/consents")
.then().extract().as(Consent.class);
consentsApi().when().post("/consents/{id}/authorisation", consent.consentId()).then().statusCode(200);
consentsApi()
.header("Consent-ID", consent.consentId())
.when()
.get("/accounts/{id}/balances", "acc-1001")
.then()
.statusCode(403)
.body("detail", containsString("ReadBalances"));
}
What’s happening:
- The consent is authorised, but only for
ReadAccountsBasic. - Asking for balances gives
403with the detailConsent consent-N lacks the permission ReadBalances. - This test builds the authorisation URL from the id instead of following the link. That’s acceptable when the URL isn’t what the test is about, but the full flow shows the better habit.
Checkpoint: run the class again. All four tests pass.
Check why a request was refused, not only that it was. A
403here can mean an unauthorised consent, an unknown consent id, which gets the sameis not authoriseddetail, or a missing permission. Only the check ondetailproves the API refused for the right reason, and not because of some other fault.
Run the Tests
Run the following command from the repository root:
1
mvn test -pl module-04 -Dtest=ChainingRequestsTest
You should see a result similar to the following:
1
2
3
4
5
6
[INFO] Running com.javanibble.module_04.section_05.ChainingRequestsTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.473 s -- in com.javanibble.module_04.section_05.ChainingRequestsTest
[INFO]
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Each test creates its own data, so the tests pass in any order and on their own.
Make a Test Fail
In createThenFollowTheLocationHeader, replace given().baseUri(api.baseUri()).port(api.port()) in the second request with consentsApi() and run the command again. You should see a result similar to the following:
1
2
3
[ERROR] Failures:
[ERROR] ChainingRequestsTest.createThenFollowTheLocationHeader:66 1 expectation failed.
Expected status code <200> but was <404>.
The customer exists, but the request went to /api/v1/api/v1/customers/..., because the base path was put in front of a Location that already contains it. A 404 right after following a link usually means a doubled prefix. Add log().uri() to see the URL that was sent.
Change it back and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
404 right after following a Location or a link | The base path was added to a path that already has it | Send the link without basePath(..) |
400 with The header Consent-ID is required | The request has no Consent-ID header | Add header("Consent-ID", ..) |
403 with is not authorised | The consent wasn’t authorised, or its id is wrong | Authorise it, and check the id you extracted |
403 with lacks the permission ReadBalances | The consent doesn’t list the permission | Add it to the consent’s permissions |
404 with is not covered by the consent | The account belongs to another customer | Use an account id from the consent’s own accounts |
Try It Yourself
Exercise 1: Leave Out the Consent-ID
Add a test called accountsNeedAConsentId that requests /accounts without a Consent-ID header, and checks that the API answers 400 with a detail that names the missing header.
Hint
This is a one-step chain: no consent is needed. Check the detail with containsString(..), as the refusal tests do.
Solution
1
2
3
4
5
6
7
8
9
@Test
void accountsNeedAConsentId() {
consentsApi()
.when()
.get("/accounts")
.then()
.statusCode(400)
.body("detail", containsString("Consent-ID"));
}
Exercise 2: Run the Flow for a Business Customer
Add a test called aBusinessCustomerWithoutBalances. Create a BUSINESS customer "Vera Visser" with the email "vera@example.nl", and request a consent with only ReadAccountsBasic. Follow the authorise link, then follow the self link and check that the status is "AUTHORISED". Read the accounts, and check that asking for the first account’s balances is refused for the missing ReadBalances permission.
Hint
Start from theFullConsentFlow. Both links are absolute paths, so send them without basePath(..). A business customer has one account, so don’t assert the number of accounts; use accounts.getFirst().
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
28
29
30
31
32
33
34
35
36
37
38
39
@Test
void aBusinessCustomerWithoutBalances() {
Customer customer = consentsApi()
.contentType(ContentType.JSON)
.body(new NewCustomer("Vera Visser", "vera@example.nl", "BUSINESS"))
.when().post("/customers")
.then().statusCode(201)
.extract().as(Customer.class);
Consent consent = consentsApi()
.contentType(ContentType.JSON)
.body(new NewConsent(customer.id(), List.of("ReadAccountsBasic")))
.when().post("/consents")
.then().statusCode(201)
.extract().as(Consent.class);
given().baseUri(api.baseUri()).port(api.port())
.when().post(consent.links().get("authorise").href())
.then().statusCode(200);
given().baseUri(api.baseUri()).port(api.port())
.when().get(consent.links().get("self").href())
.then().statusCode(200)
.body("status", equalTo("AUTHORISED"));
List<Account> accounts = consentsApi()
.header("Consent-ID", consent.consentId())
.when().get("/accounts")
.then().statusCode(200)
.extract().as(new TypeRef<List<Account>>() {});
consentsApi()
.header("Consent-ID", consent.consentId())
.when()
.get("/accounts/{id}/balances", accounts.getFirst().accountId())
.then()
.statusCode(403)
.body("detail", containsString("ReadBalances"));
}
Summary
You built ChainingRequestsTest, which follows a Location header, runs the consent flow from a new customer to a balance, and proves that an unauthorised consent or a missing permission opens nothing. The flow no longer depends on consent-1 or on a URL pattern the test made up.
- A chain sends, validates and extracts at every step, and passes what it extracted to the next request.
- Map a response to a record when the next steps need several values, and use
extract().path(..)when they need one. - Follow the
Locationheaders and links the API returns; send an absolute path without a base path, or it gets the prefix twice. - Create the data each test needs, so tests pass in any order and on their own.
- Test the refusals as carefully as the happy path, and check the
detailso a refusal fails for the right reason.
Here are the commands you used in this guide:
1
mvn test -pl module-04 -Dtest=ChainingRequestsTest
What’s Next
Next: you’ve completed Module 4. Continue with Module 5: Reusable Specifications and Configuration, starting with Build Reusable Request Specifications in REST Assured, which replaces helpers like consentsApi() with reusable request specifications.
The code:
- The finished test class:
ChainingRequestsTest.java - The code and run commands for this module: Module 4 README
Go deeper:
- REST Assured Usage wiki, for extracting values and using them in later requests.
- The Berlin Group, whose NextGenPSD2 framework defines the open banking consent model this API simplifies.
Related guides:
- Extract Values From a Response in REST Assured, for why you validate before you extract.
- Check Session Cookie Security in REST Assured, for another security test that checks more than the happy path.
