Control Where REST Assured Requests Go
Learn how REST Assured builds a URL from baseUri, port, basePath and the path, when an absolute URL wins, and why static defaults on RestAssured are global state.
Your account tests fail with Connection refused on one machine and a 404 on another, while a third test passes only when the whole suite runs. All three have the same cause: nobody was sure where each request actually went. In this guide, you’ll learn how REST Assured builds the URL of every request, and set each part of it on purpose.
Level: Beginner · Time: 20 minutes · Part of: Module 1: Foundations, section 3
What You’ll Build
You’ll build two test classes. PerRequestConfigurationTest sets the URL parts on each request, and StaticConfigurationTest sets them once as static defaults on RestAssured. Together they prove which value wins when both are set.
The main test sends this request and checks this response:
1
2
3
4
5
6
7
GET /api/v1/accounts/acc-1004 HTTP/1.1
Host: localhost:<port>
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
{"id":"acc-1004","owner":"Emily Clarke", ...}
When you’re done, Maven reports five passing tests across the two classes:
1
2
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- Set the URL parts on each request.
- Override everything with an absolute URL.
- Set static defaults on
RestAssuredand reset them.
What You Need
- About 20 minutes
- JDK 26 or later
- Maven 3.9 or later
- An IDE (IntelliJ IDEA, VS Code or Eclipse)
- Knowledge: you can start the Accounts API and send a request with
baseUri(..)andport(..), as taught in Send Your First REST Assured Request, and you know the full and short forms of a test from Take Apart a REST Assured Test.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: create both classes in a new
section_03package next to the classes from the previous sections, and follow every heading below. - Skip ahead: open the finished classes (
PerRequestConfigurationTest.javaandStaticConfigurationTest.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 Send Your First REST Assured Request.
Out of scope: this guide doesn’t cover reusable request specifications, which replace static defaults in larger suites; they’re taught in Module 5.
Understand How REST Assured Builds a URL
The problem. A test that sends its request to the wrong place rarely fails with a useful message. A wrong port gives Connection refused, a missing /api/v1 prefix gives a 404, and a value left behind by an earlier test class can make a broken test pass.
The concept. REST Assured builds the URL of every request from four parts:
1
2
http://localhost : 54321 /api/v1 /accounts/acc-1004
└─── baseUri ──┘ └port┘ └base┘ └──── path ──────┘
baseUriis the scheme and host, such ashttp://localhost.portis the TCP port, such as the free port the Accounts API picked.basePathis a prefix shared by many endpoints, such as/api/v1.- The path is the argument to
get(..),post(..)and the other methods.
When you call get(path), REST Assured resolves the URL in this order:
- If the path is a complete URL, it’s used as it is.
- Otherwise, each part set on the request is used.
- Any part not set on the request comes from the static defaults
RestAssured.baseURI,RestAssured.portandRestAssured.basePath. - Without either, REST Assured falls back to
http://localhost, port8080and an empty base path.
When to use each. Values set on the request make each test independent and safe to run in parallel, at the cost of a few repeated lines. Static defaults make tests shorter, but they’re global state for the whole JVM. Use them only in small suites that never run classes in parallel, and always reset them.
Set where a request goes on the request, not in global state.
Meet the API Under Test
This guide uses two endpoints of the Accounts API:
| Method | Path | Purpose |
|---|---|---|
GET | /api/health | Report whether the service is up |
GET | /api/v1/accounts/{id} | Fetch one account |
The account endpoints share the prefix /api/v1, which the module exposes as the constant AccountsApi.BASE_PATH. The health endpoint doesn’t have that prefix.
For acc-1004, the account endpoint returns a response similar to the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
{
"id": "acc-1004",
"iban": "GB33BUKB20201555555555",
"owner": "Emily Clarke",
"type": "CURRENT",
"currency": "GBP",
"balance": 980.00,
"status": "ACTIVE",
"openedOn": "2023-06-05"
}
For acc-1002, it returns an account whose type is "SAVINGS".
Your tests check three things:
- The
ownerfield ofacc-1004,"Emily Clarke", which proves the base path was applied. - The
typefield ofacc-1002,"SAVINGS", which proves the static defaults were applied. - The status code of
/api/health, which proves an absolute URL or an overridden base path reached the right endpoint.
Set the URL Parts on Each Request
The first class sets every part of the URL on each request, so no test depends on anything outside itself.
Set Up the Per-Request Class
Goal: create the first test class and start the API.
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
package com.javanibble.module_01.section_03;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import com.javanibble.accounts.AccountsApi;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class PerRequestConfigurationTest {
private static AccountsApi api;
@BeforeAll
static void startApi() {
api = AccountsApi.start();
}
@AfterAll
static void stopApi() {
api.close();
}
}
What’s happening:
- The class starts and stops the Accounts API as in the previous sections.
- There are no static defaults anywhere, so each test must say where its request goes.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Use a Base Path
Goal: put the /api/v1 prefix in one place, so the path holds only the part that changes.
1
2
3
4
5
6
7
8
9
10
11
12
@Test
void basePathIsPutInFrontOfEveryPath() {
given()
.baseUri(api.baseUri())
.port(api.port())
.basePath(AccountsApi.BASE_PATH)
.when()
.get("/accounts/acc-1004")
.then()
.statusCode(200)
.body("owner", equalTo("Emily Clarke"));
}
What’s happening:
basePath(AccountsApi.BASE_PATH)sets the prefix/api/v1for this request.get("/accounts/acc-1004")gives only the rest of the path, so the request goes to/api/v1/accounts/acc-1004.body("owner", equalTo("Emily Clarke"))proves the request reached the right account.
Checkpoint: run PerRequestConfigurationTest from your IDE. One test runs and passes.
Don’t repeat the prefix in the path. With a base path of
/api/v1, a call toget("/api/v1/accounts/acc-1004")goes to/api/v1/api/v1/accounts/acc-1004and returns a404.
Put the Port in the Base URI
Goal: give the host and port as one string instead of two settings.
1
2
3
4
5
6
7
8
9
@Test
void thePortCanAlsoBePartOfTheBaseUri() {
given()
.baseUri("http://localhost:" + api.port())
.when()
.get("/api/health")
.then()
.statusCode(200);
}
What’s happening:
baseUri("http://localhost:" + api.port())holds the scheme, host and port together, such ashttp://localhost:54321.- There’s no
port(..)call, because the base URI already contains the port. - There’s no
basePath(..)call either, because the health endpoint has no/api/v1prefix.
This form is convenient when the address comes from configuration as one string.
Checkpoint: run the class again. Two tests pass.
Override Everything with an Absolute URL
A complete URL in get(..) is step 1 of the resolution order, so it wins over every other setting.
Prove That the Absolute URL Wins
Goal: show that an absolute URL ignores the base URI and port set on the request.
To prove it, this test sets a port that nothing listens on, and the request still succeeds:
1
2
3
4
5
6
7
8
9
10
@Test
void anAbsoluteUrlWinsOverBaseUriAndPort() {
given()
.baseUri("http://localhost")
.port(1)
.when()
.get("http://localhost:" + api.port() + "/api/health")
.then()
.statusCode(200);
}
What’s happening:
port(1)points the request at a port where nothing listens. If REST Assured used it, the test would fail withConnection refused.get("http://localhost:" + api.port() + "/api/health")is a complete URL with scheme, host and port, so REST Assured uses it as it is.- The test passing is the proof: the absolute URL won over
baseUri(..)andport(..).
Checkpoint: run the class again. All three tests pass.
An absolute URL is handy for following a link that the API returned, such as a
Locationheader. For your own endpoints, preferbaseUri,portandbasePath, so the address lives in one place.
Set Static Defaults on RestAssured
RestAssured has public static fields for the same settings. Set them once, and every request in the JVM that doesn’t set its own value uses them.
Set the Defaults and Reset Them
Goal: create the second test class, set the defaults when the API starts and undo them when it stops.
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
package com.javanibble.module_01.section_03;
import static io.restassured.RestAssured.get;
import static org.hamcrest.Matchers.equalTo;
import com.javanibble.accounts.AccountsApi;
import io.restassured.RestAssured;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class StaticConfigurationTest {
private static AccountsApi api;
@BeforeAll
static void startApiAndSetDefaults() {
api = AccountsApi.start();
RestAssured.baseURI = api.baseUri();
RestAssured.port = api.port();
RestAssured.basePath = AccountsApi.BASE_PATH;
}
@AfterAll
static void resetDefaultsAndStopApi() {
RestAssured.reset();
api.close();
}
}
What’s happening:
RestAssured.baseURI,RestAssured.portandRestAssured.basePathare static fields, so setting them changes every later request in the JVM.RestAssured.reset()puts them back tohttp://localhost, port8080and an empty base path.- The reset runs before
api.close(), so no later class can inherit the port of a server that has stopped.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Always pair static defaults with
RestAssured.reset()in@AfterAll. Without it, a later test class that forgets its own port passes or fails depending on which class ran first, and it fails when you run it on its own.
Use the Defaults
Goal: send a request that relies entirely on the static defaults.
1
2
3
4
@Test
void requestsUseTheStaticDefaults() {
get("/accounts/acc-1002").then().statusCode(200).body("type", equalTo("SAVINGS"));
}
What’s happening:
- The static
get(..)sets nothing on the request, so the base URI, port and base path all come from the defaults. - The request goes to
/api/v1/accounts/acc-1002, andbody("type", equalTo("SAVINGS"))proves it reached the right account.
Checkpoint: run StaticConfigurationTest from your IDE. One test runs and passes.
Override a Default for One Request
Goal: show that a value on the request still wins over the default.
The health endpoint has no /api/v1 prefix, so this test replaces the base path for one request:
1
2
3
4
5
6
7
8
9
@Test
void aValueOnTheRequestOverridesTheDefault() {
RestAssured.given()
.basePath("/api")
.when()
.get("/health")
.then()
.statusCode(200);
}
What’s happening:
basePath("/api")replaces the default/api/v1for this request only.- The base URI and port still come from the defaults, so the request goes to
/api/healthon the running API. - The class has no static import for
given, so the test callsRestAssured.given()directly.
Checkpoint: run the class again. Both tests pass.
Two classes that set different static defaults overwrite each other’s values when they run in parallel, and the failures that follow are intermittent. Module 5 replaces static defaults with reusable request specifications, which are as short and have neither problem.
Run the Tests
Run the following command from the repository root:
1
mvn test -pl module-01 -Dtest='PerRequestConfigurationTest,StaticConfigurationTest'
You should see a result similar to the following:
1
2
3
4
5
6
7
8
[INFO] Running com.javanibble.module_01.section_03.StaticConfigurationTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.387 s -- in com.javanibble.module_01.section_03.StaticConfigurationTest
[INFO] Running com.javanibble.module_01.section_03.PerRequestConfigurationTest
[INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.014 s -- in com.javanibble.module_01.section_03.PerRequestConfigurationTest
[INFO]
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Make a Test Fail
Remove the .basePath(AccountsApi.BASE_PATH) line from basePathIsPutInFrontOfEveryPath and run the command again. You should see a result similar to the following:
1
2
3
[ERROR] Failures:
[ERROR] PerRequestConfigurationTest.basePathIsPutInFrontOfEveryPath:45 1 expectation failed.
Expected status code <200> but was <404>.
Without the base path, the request goes to /accounts/acc-1004, which doesn’t exist, so the API answers 404. A 404 from an endpoint you know exists usually means a missing or repeated prefix.
Put the .basePath(AccountsApi.BASE_PATH) line back and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
» Connect Connection refused | No port is set on the request or as a default, so the request goes to port 8080 | Add .port(api.port()), or put the port in the base URI |
Expected status code <200> but was <404> | The /api/v1 prefix is missing, or it’s in both basePath(..) and the path | Set the prefix in exactly one place |
| A test passes in the full suite but fails on its own | It relies on static defaults that another class set and didn’t reset | Set the URL parts on the request, and call RestAssured.reset() in every class that sets defaults |
Try It Yourself
Exercise 1: Request Another Account with a Base Path
A request to GET /api/v1/accounts/acc-1003 returns a response body similar to the following:
1
2
3
4
5
6
7
8
9
10
{
"id": "acc-1003",
"iban": "NL20INGB0001234567",
"owner": "Jan Jansen",
"type": "CURRENT",
"currency": "EUR",
"balance": -42.10,
"status": "BLOCKED",
"openedOn": "2017-11-30"
}
Add a test called basePathWorksForAnotherAccount to PerRequestConfigurationTest. Use basePath(..) and a path parameter to request the account, and check the status code and the owner field.
Hint
Copy basePathIsPutInFrontOfEveryPath. Replace the path with "/accounts/{id}" and pass the id as an extra argument to get(..), as you did in the previous section.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
@Test
void basePathWorksForAnotherAccount() {
given()
.baseUri(api.baseUri())
.port(api.port())
.basePath(AccountsApi.BASE_PATH)
.when()
.get("/accounts/{id}", "acc-1003")
.then()
.statusCode(200)
.body("owner", equalTo("Jan Jansen"));
}
Exercise 2: Beat the Static Defaults with an Absolute URL
StaticConfigurationTest sets a default base path of /api/v1, which the health endpoint doesn’t have. Add a test called anAbsoluteUrlWinsOverTheStaticDefaults that reaches /api/health without calling given() or basePath(..), and checks the status code and the status field.
Hint
An absolute URL is step 1 of the resolution order, so it wins over static defaults as well as values on the request. Build it from api.port().
Solution
1
2
3
4
5
6
7
@Test
void anAbsoluteUrlWinsOverTheStaticDefaults() {
get("http://localhost:" + api.port() + "/api/health")
.then()
.statusCode(200)
.body("status", equalTo("UP"));
}
Summary
You built PerRequestConfigurationTest and StaticConfigurationTest, which set where a request goes on the request, with an absolute URL and as static defaults. The next time a test fails with Connection refused or an unexpected 404, you know which four parts to check.
- REST Assured builds every URL from
baseUri,port,basePathand the path. - A complete URL in
get(..)wins over every other setting, on the request or as a default. - A value set on the request wins over the static default for that request only.
- Without a port on the request or as a default, REST Assured sends the request to port 8080.
- Static defaults are global state for the whole JVM, so reset them with
RestAssured.reset()and don’t run classes that set them in parallel.
Here are the commands you used in this guide:
1
mvn test -pl module-01 -Dtest='PerRequestConfigurationTest,StaticConfigurationTest'
What’s Next
Next: continue with Check Every Part of an HTTP Response, which checks status lines, content types, headers and body fields in more depth.
The code:
- The finished test classes:
PerRequestConfigurationTest.javaandStaticConfigurationTest.java - The code and run commands for this module: Module 1 README
Go deeper:
- REST Assured Usage wiki, for default values and the other static settings on
RestAssured. - REST Assured javadoc, for
RestAssured.reset()and every method onRequestSpecification.
Related guides:
- Take Apart a REST Assured Test, for the absolute-URL forms that leave out
given(). - Module 5: Reusable Specifications and Configuration, for the request specifications that replace static defaults.
