Post

Send Your First REST Assured Request

Write a JUnit test that starts a real Accounts API, sends it an HTTP request with REST Assured and checks both the status code and the JSON body.

Send Your First REST Assured Request

Your team has built an Accounts API, and the only proof that it works is someone running curl before each release and reading the output by eye. Nobody notices when the health endpoint starts reporting DOWN with a 200 status. In this guide, you’ll replace that manual check with an automated REST Assured test that sends a real HTTP request and checks the response for you.

Level: Beginner · Time: 15 minutes · Part of: Module 1: Foundations, section 1

What You’ll Build

You’ll build a test class called FirstRequestTest with two tests. Together they prove that the Accounts API’s health endpoint answers with 200 OK and reports that the service is up.

Both tests send this request and check this response:

1
2
3
4
5
6
7
GET /api/health HTTP/1.1
Host: localhost:<port>

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

{"status":"UP"}

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

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

In this guide, you will:

  • Start the API under test before your tests and stop it after them.
  • Send a request and check the status code.
  • Check the JSON body.

What You Need

  • About 15 minutes
  • JDK 26 or later
  • Maven 3.9 or later
  • An IDE (IntelliJ IDEA, VS Code or Eclipse)
  • Knowledge: you can write and run a plain JUnit test with @Test. You don’t need any earlier REST Assured knowledge.

Nothing else has to be installed. The repository uses REST Assured 6.3.0, JUnit 6.1.3 and Jackson 3.2.3, and Maven downloads them for you.

How to Complete This Guide

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

  • Build it step by step: create FirstRequestTest from scratch and follow every heading below. This is the first section, so there is no earlier code to start from.
  • Skip ahead: open the finished class (FirstRequestTest.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

Out of scope: this guide doesn’t explain the types behind given(), when() and then(), or the shorter ways to write a test. Those are taught in Take Apart a REST Assured Test.

Understand REST Assured

The problem. A unit test calls a Java method and checks what it returns. A client only ever sees an HTTP endpoint through HTTP, though. To prove that GET /api/health answers with 200 and a body that says the service is up, you have to send a real request over a real socket and check the real response. That’s what the person running curl was doing by hand.

The concept. REST Assured is a Java library, a domain-specific language, for testing HTTP APIs. You describe a request, send it and check the response in one readable chain:

  • given() starts the request specification: where the request goes and what it carries, such as base URI, port, headers and body.
  • when() starts the action: it sends the request with a method such as get(..) or post(..).
  • then() starts the validation: each call, such as statusCode(..) or body(..), checks one part of the response and fails the test on a mismatch.

When to use it, and when not to. You could write the same test with the JDK’s HttpClient, but you would then parse the JSON, compare values and build the failure messages yourself. You could also mock the HTTP layer, but that tests your mock rather than your API. A real server checks routing, status codes, headers and serialisation as a client sees them. Keep plain unit tests for business logic you can call directly, because they are faster and fail closer to the bug.

Test an HTTP API through HTTP, not through a mock.

Meet the API Under Test

This module tests a small, read-only Accounts API. It runs on the JDK’s built-in HTTP server, writes JSON with Jackson and starts on a free port. This guide uses one endpoint:

MethodPathPurpose
GET/api/healthReport whether the service is up

Send a GET request to /api/health, and you get a response similar to the following:

1
2
3
4
5
6
7
8
9
GET /api/health HTTP/1.1

HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
X-request-id: a9bb8616-2ea6-442e-a3f5-94b1bee71545
Content-length: 15
Cache-control: no-store

{"status":"UP"}

Your tests check two things in this response:

  • The status line, 200 OK.
  • The status field in the JSON body, whose value is the string "UP".

The account endpoints used in later sections are listed in the Module 1 README.

Start the API Under Test

Every test in this module starts the Accounts API once per test class, on a free port, and stops it when the class is done. Nothing is started by hand, and no test depends on a port that might already be taken.

Hold the API in a Static Field

Goal: create the test class and give it a place to keep the running server.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.javanibble.module_01.section_01;

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 FirstRequestTest {

    private static AccountsApi api;
}

What’s happening:

  • AccountsApi is the module’s test server. The api field holds a handle to it, which every test in the class uses.
  • The field is static because the @BeforeAll and @AfterAll methods that set and clear it are static, and a static method can’t reach an instance field.
  • given() comes from REST Assured and equalTo(..) from Hamcrest. REST Assured is used through static imports, which keep the chain short.

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

Hamcrest is a dependency of REST Assured, so you don’t add it to the POM. Matchers such as hasItems, containsString and lessThan are always available.

Start the Server Before All Tests

Goal: start the Accounts API once, before the first test in the class runs.

1
2
3
4
@BeforeAll
static void startApi() {
    api = AccountsApi.start();
}

What’s happening:

  • @BeforeAll tells JUnit to run this method once, before any test in the class.
  • AccountsApi.start() binds the server to a free port and returns a handle to it.
  • Starting one server per test class means classes don’t share state, and you can run any class on its own from your IDE.

Checkpoint: the class still compiles. JUnit runs @BeforeAll methods only when a class has at least one test, so you’ll see the server start once you add the first test.

Stop the Server After All Tests

Goal: stop the server and free its port when the class is done.

1
2
3
4
@AfterAll
static void stopApi() {
    api.close();
}

What’s happening:

  • @AfterAll tells JUnit to run this method once, after the last test in the class.
  • close() stops the server and releases the port and threads it held.

Checkpoint: the lifecycle is complete. The class compiles, and the next section adds a test that uses it.

Without @AfterAll, every test class leaves a server running until the JVM exits. In a large build, those servers hold ports and threads that no test uses any more. Pair every start() with a close().

Send a Request and Check the Status Code

The server is running, so you can now send it a request.

Write the Status Code Test

Goal: send GET /api/health and check that the API answers with 200.

1
2
3
4
5
6
7
8
9
10
@Test
void healthEndpointAnswersWith200() {
    given()
        .baseUri(api.baseUri())
        .port(api.port())
    .when()
        .get("/api/health")
    .then()
        .statusCode(200);
}

What’s happening:

  • given().baseUri(api.baseUri()) points the request at http://localhost.
  • .port(api.port()) uses the port the server picked when it started.
  • .when().get("/api/health") sends the request over HTTP and returns the response.
  • .then().statusCode(200) fails the test unless the status line is 200.

Read the chain aloud and it is a sentence: given this base URI and port, when I get /api/health, then the status code is 200. This is Arrange, Act, Assert, written for HTTP.

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

Without port(..), REST Assured sends the request to port 8080 on localhost. If nothing listens there, you get a ConnectException instead of an assertion failure. Always pass the port the API reports.

Check the JSON Body

A status code alone doesn’t prove much. If the endpoint answered 200 with {"status":"DOWN"}, the first test would stay green while the API reports the wrong state. That’s the bug from the opening scenario.

Add a Body Check

Goal: check that the body’s status field says "UP", as well as the status code.

The request is the same as in the previous test. What changes is the extra body(..) call after statusCode(..):

1
2
3
4
5
6
7
8
9
10
11
@Test
void healthEndpointReportsThatItIsUp() {
    given()
        .baseUri(api.baseUri())
        .port(api.port())
    .when()
        .get("/api/health")
    .then()
        .statusCode(200)
        .body("status", equalTo("UP"));
}

What’s happening:

  • The first argument to body(..), "status", is a path: an expression that picks a value out of the response body. Here it picks the string "UP" from {"status":"UP"}.
  • The second argument, equalTo("UP"), is a Hamcrest matcher: an object that decides whether that value is acceptable.
  • You never parse the JSON yourself. REST Assured sees the application/json content type, parses the body and looks the path up for you.

Checkpoint: run FirstRequestTest again. Both tests pass.

statusCode(..) checks the HTTP status line, such as 200. body("status", ..) reads a JSON field that happens to be called status. They are unrelated, so check each with its own method.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-01 -Dtest=FirstRequestTest

You should see a result similar to the following:

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

Make a Test Fail

Change equalTo("UP") to equalTo("DOWN") in healthEndpointReportsThatItIsUp and run the command again. You should see a result similar to the following:

1
2
3
4
5
[ERROR] Failures:
[ERROR]   FirstRequestTest.healthEndpointReportsThatItIsUp:58 1 expectation failed.
JSON path status doesn't match.
Expected: DOWN
  Actual: UP

The message names the path that was checked, the value you expected and the value the API sent. Reading these messages is the topic of Read REST Assured Failure Messages.

Change equalTo("DOWN") back to equalTo("UP") and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
java.net.ConnectException: Connection refusedThe request has no port(..), so it goes to port 8080Add .port(api.port()) to given()
non-static variable api cannot be referenced from a static contextThe api field isn’t staticDeclare it as private static AccountsApi api;
error: release version 26 not supportedMaven is running on an older JDKPoint JAVA_HOME at JDK 26 or later and check with mvn -v

Try It Yourself

Exercise 1: Check an Unknown Account

The Accounts API answers GET /api/v1/accounts/{id} with 404 Not Found when the id doesn’t exist. Add a test called unknownAccountAnswersWith404 that requests /api/v1/accounts/acc-9999 and checks the status code.

Hint

Copy healthEndpointAnswersWith200. Change only the path and the expected status code.

Solution
1
2
3
4
5
6
7
8
9
10
@Test
void unknownAccountAnswersWith404() {
    given()
        .baseUri(api.baseUri())
        .port(api.port())
    .when()
        .get("/api/v1/accounts/acc-9999")
    .then()
        .statusCode(404);
}

Exercise 2: Check an Account’s Details

A request to GET /api/v1/accounts/acc-1004 returns a response body similar to the following:

1
2
3
4
5
6
7
8
9
10
{
    "id": "acc-1004",
    "iban": "GB33BUKB20201555555555",
    "owner": "Emily Clarke",
    "type": "CURRENT",
    "currency": "GBP",
    "balance": 980.00,
    "status": "ACTIVE",
    "openedOn": "2023-06-05"
}

Add a test called accountEndpointReturnsTheAccount. It should check that the status code is 200, and that the id, owner and currency fields hold the values shown.

Hint

You can chain several body(..) calls after statusCode(..), one per field.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void accountEndpointReturnsTheAccount() {
    given()
        .baseUri(api.baseUri())
        .port(api.port())
    .when()
        .get("/api/v1/accounts/acc-1004")
    .then()
        .statusCode(200)
        .body("id", equalTo("acc-1004"))
        .body("owner", equalTo("Emily Clarke"))
        .body("currency", equalTo("GBP"));
}

Summary

You built FirstRequestTest, which starts the Accounts API, sends it a real HTTP request and checks both the status code and the JSON body. Nobody has to read curl output by eye any more.

  • Start the API under test in a static @BeforeAll method and stop it in @AfterAll, so each test class has its own server.
  • Point given() at the running API with baseUri(..) and port(..), or the request goes to port 8080.
  • Send the request with when().get(..) and check the response after then().
  • Check the body as well as the status code, because a 200 with the wrong body is still a bug.
  • Read a body value with a path such as "status" and check it with a Hamcrest matcher such as equalTo(..).

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-01 -Dtest=FirstRequestTest

What’s Next

Next: continue with Take Apart a REST Assured Test, which takes the given/when/then chain apart into the types behind it.

The code:

Go deeper:

Related guides:

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