REST Assured Guide - Module 1 Section 1

REST Assured Guide - Module 1 Section 1

TWrite a REST Assured test that sends a real HTTP request to a running API and checks the status code and the JSON body.

Introduction

Learning goal: Write a REST Assured test that sends a real HTTP request to a running API and checks the status code and the JSON body. Level: Beginner · Time: 15 minutes

What you’ll build: a test class called FirstRequestTest with two tests. Both send the following request to the Accounts API, and together they check the status code and the body of the response:

GET /api/health HTTP/1.1
Host: localhost:<port>

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

{"status":"UP"}

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.
  • Test your API and make a test fail on purpose.

This guide is section 1 of Module 1: Foundations of the REST Assured Guide.

Before You Begin

This guide assumes you can write and run a plain JUnit test with @Test. You don’t need any earlier REST Assured knowledge.

You need the following:

  • JDK 26 or later.
  • Maven 3.9 or later.
  • An IDE, such as IntelliJ IDEA, Eclipse or VS Code.

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.

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

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

How to follow this guide: you can build the test step by step, or open the finished FirstRequestTest and read along.

What this guide doesn’t cover: the types behind given(), when() and then(), and the shorter ways to write a test, are taught in Section 2.

Why Use REST Assured?

A unit test calls a Java method and checks what it returns. The code behind an HTTP endpoint is different, because a client only ever sees it through HTTP. To prove that GET /api/health answers with 200 and a JSON body that says the service is up, you have to send a real request over a real socket and check the real response.

REST Assured is a Java library, or domain-specific language, for testing HTTP APIs. You describe a request, send it and check the response in one readable chain. Every test has three parts:

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

You could write the same test with the JDK’s HttpClient. You would then parse the JSON, compare strings and build the error messages yourself. REST Assured reads the body with a path language, checks it with Hamcrest matchers and writes a clear failure message for you.

You could also mock the HTTP layer instead of starting a server. That tests your mock, not your API. A real server checks routing, status codes, headers and serialisation as a client sees them, and this one starts in milliseconds on a free port.

Use REST Assured when the thing you want to prove is visible over HTTP. Keep plain unit tests for business logic that 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

The 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 only its health endpoint.

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

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"}

Notice that the body is a JSON object with one field, status, whose value is the string "UP". The second test reads exactly that field. The account endpoints used in later sections are listed in the Module 1 README.

Start the API Under Test

Every test in this module follows the same four steps:

  1. Start the API: @BeforeAll starts the Accounts API on a free port, once for the whole test class.
  2. Arrange: given() describes the request, with the base URI http://localhost and the port the API picked.
  3. Act: when().get("/api/health") sends the request over HTTP.
  4. Assert: then() checks the status code and the body of the response.

When the last test in the class has run, @AfterAll stops the server. Nothing has to be started by hand, and no test depends on a port that might already be taken.

Hold the API in a Static Field

Create the test class with a field for the running API:

module-01/src/test/java/com/javanibble/module_01/section_01/FirstRequestTest.java

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;
}

The field holds a handle to the running server, which every test in the class uses. It is static because the @BeforeAll and @AfterAll methods that set and clear it are static.

Don’t:

private AccountsApi api;    // wrong: a static @BeforeAll method can't set an instance field

The class no longer compiles, because a static method can’t reach an instance field.

Do:

private static AccountsApi api;

The static field lives as long as the class, so the server it holds is shared by every test in it.

Start the Server Before All Tests

Add the following method to FirstRequestTest:

@BeforeAll
static void startApi() {
    api = AccountsApi.start();
}

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

Stop the Server After All Tests

Add the following method to FirstRequestTest:

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

JUnit runs this method once, after the last test in the class. close() stops the server and frees its port.

Pitfall: Forgetting to stop the server. 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().

Write Your First REST Assured Test

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

Send a Request and Check the Status Code

Add the following method to FirstRequestTest:

@Test
void healthEndpointAnswersWith200() {
    given()                                 // Arrange: describe the request
        .baseUri(api.baseUri())             //   http://localhost
        .port(api.port())                   //   the port the API picked
    .when()                                 // Act: send it
        .get("/api/health")
    .then()                                 // Assert: check the response
        .statusCode(200);
}

api.baseUri() returns http://localhost, and api.port() returns the port the server picked. 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.

Pitfall: Forgetting the port. 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. A 200 with the wrong body is still a bug.

Don’t:

.then()
    .statusCode(200);    // wrong on its own: passes even if the body says "DOWN"

The test stays green while the endpoint reports the wrong state.

Do:

.then()
    .statusCode(200)
    .body("status", equalTo("UP"));

At least one body(..) check proves that the response means what you expect.

Add the following method to FirstRequestTest:

@Test
void healthEndpointReportsThatItIsUp() {
    given()
        .baseUri(api.baseUri())
        .port(api.port())
    .when()
        .get("/api/health")
    .then()
        .statusCode(200)
        .body("status", equalTo("UP"));     // "status" is a path into the JSON body {"status":"UP"}
}

The request is the same as before; what changed is the body(..) check after the status code. Its first argument, "status", is a path: an expression that picks a value out of the response body, here the string "UP". Its second argument, equalTo("UP"), is a Hamcrest matcher: an object that decides whether that value is acceptable.

Notice that you never parse the JSON yourself. REST Assured sees the application/json content type, parses the body and looks the path up for you.

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

Use the Static Imports

REST Assured is used through static imports, which keep the chain short. The test class needs these two:

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

given() comes from REST Assured and equalTo(..) from Hamcrest. 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.

Test Your API

Run the following command from the repository root:

mvn test -pl module-01 -Dtest=FirstRequestTest

You should see a result similar to the following:

[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

Both tests pass.

Make a test fail

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

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

The message names the path, the expected value and the actual value. Reading these messages is the topic of Section 6, but it is worth seeing one now. Change equalTo("DOWN") back to equalTo("UP") and run the tests once more to confirm they pass.

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
@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:

{
    "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
@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"));
}

Recap

You built FirstRequestTest, which starts the Accounts API, sends a real HTTP request to it and checks both the status code and the JSON body. A REST Assured test is a real HTTP round trip written as one sentence: given a request, when it is sent, then the response looks like this. That is the foundation every later test in this guide builds on.

  • 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 the body 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:

git clone https://github.com/javanibble/rest-assured-examples.git
cd rest-assured-examples
mvn test -pl module-01 -Dtest=FirstRequestTest

What’s Next

Continue with The Anatomy of a REST Assured Test, which takes the given/when/then chain apart into the types behind it.

For more depth: