Skip to content
javahacks.dev
Testing

How to Use REST Assured for API Tests in Java Projects

Write readable API tests with REST Assured: given when then, JSON path checks, request specs, authentication, schema validation and Spring Boot setup.

8 min read
Summarize in AI
Flat illustration of a test report with one failing test, with the OpenJDK, Spring Boot, Spring and GitHub Actions logos.

An API is a contract expressed in HTTP: this path, this method, this body gives that status and that JSON. The tests that matter most for an API read like the contract. REST Assured, a long standing Java library, makes them do that. Its fluent syntax mirrors how an API is described, a request with some inputs, an action, expected outputs, and it handles JSON, XML, headers, cookies, authentication and file uploads without boilerplate. This post sets it up with a Spring Boot application, builds tests from a basic call up to shared specifications and schema validation, shows the debugging output and explains where REST Assured fits next to MockMvc and Playwright. For a browser driven test of the same application, see the Playwright for Java guide.

Setup

REST Assured is a test dependency. For a Spring Boot application add it with JUnit and the JSON schema module if you need schema checks:

pom.xmlXML
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.5.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>5.5.0</version>
    <scope>test</scope>
</dependency>

Point it at the application under test. With @SpringBootTest(webEnvironment = RANDOM_PORT) the server listens on a free port that the test class can read:

src/test/java/dev/javahacks/api/OrderApiTest.javajava
package dev.javahacks.api;

import io.restassured.RestAssured;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;

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

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class OrderApiTest {

    @LocalServerPort
    int port;

    @BeforeEach
    void configure() {
        RestAssured.baseURI = "http://localhost";
        RestAssured.port = port;
    }

    @Test
    void getReturnsAnExistingOrder() {
        given()
                .accept("application/json")
        .when()
                .get("/api/orders/{id}", 1)
        .then()
                .statusCode(200)
                .contentType("application/json")
                .body("id", equalTo(1))
                .body("status", equalTo("NEW"))
                .body("lines", hasSize(2))
                .body("lines[0].sku", equalTo("BK-1"));
    }
}

The three keywords carry the structure. given() sets up the request: headers, parameters, body, authentication. when() performs it: the verb and the path, with {id} placeholders filled from the arguments. then() asserts on the response. The body("lines[0].sku", ...) argument is a Groovy GPath expression into the JSON, and equalTo, hasSize and the rest are Hamcrest matchers. Because the syntax is a chain, the test reads as a sentence, which is the main reason to choose the library.

Static state is a trap here: RestAssured.baseURI and port are global fields. Set them in @BeforeEach, as above, and reset with RestAssured.reset() in @AfterEach if other test classes run in the same JVM with a different port, or the second class talks to the first one's server.

Requests with bodies, parameters and headers

java
@Test
void createReturnsLocationAndTheNewOrder() {
    given()
            .contentType("application/json")
            .body("""
                  {"customerEmail": "[email protected]", "lines": [{"sku": "BK-1", "quantity": 2}]}
                  """)
    .when()
            .post("/api/orders")
    .then()
            .statusCode(201)
            .header("Location", matchesPattern("/api/orders/\\d+"))
            .body("customerEmail", equalTo("[email protected]"));
}

@Test
void listSupportsFilteringAndPaging() {
    given()
            .queryParam("status", "NEW")
            .queryParam("page", 0)
            .queryParam("size", 5)
            .header("X-Request-Id", "test-123")
    .when()
            .get("/api/orders")
    .then()
            .statusCode(200)
            .body("content.size()", lessThanOrEqualTo(5))
            .body("content.status", everyItem(equalTo("NEW")))
            .body("totalElements", greaterThanOrEqualTo(0));
}

A text block keeps the JSON readable. You can also pass a Java object or a Map, and REST Assured serialises it with Jackson when it is on the classpath, which couples the test to your model classes and hides the wire format; for contract tests, literal JSON is clearer, because it is what a client sends. In the second test, content.status with everyItem asserts a property of every element in the list in one line, the kind of check that is tedious in hand written parsing code.

Extracting values and chaining requests

Sometimes a test needs a value from one response to build the next request: create, then fetch what was created. extract() returns pieces of the response:

java
@Test
void anOrderCanBeCreatedAndThenFetched() {
    int id = given()
            .contentType("application/json")
            .body("{\"customerEmail\": \"[email protected]\", \"lines\": [{\"sku\": \"BK-2\", \"quantity\": 1}]}")
    .when()
            .post("/api/orders")
    .then()
            .statusCode(201)
            .extract().path("id");

    given()
    .when()
            .get("/api/orders/{id}", id)
    .then()
            .statusCode(200)
            .body("customerEmail", equalTo("[email protected]"));
}

extract().path("id") returns the value at that JSON path, here an Integer. extract().as(OrderResponse.class) deserialises the whole body into an object, useful for complex assertions with AssertJ. Keep such chains short: a test that creates five resources in sequence is testing a workflow and will be hard to diagnose; the setup is better done directly through the application's repositories, with the API call under test being the only HTTP request.

Authentication

REST Assured has built in support for the common schemes:

java
given().auth().basic("ana", "correct horse").when().get("/api/me").then().statusCode(200);

given().auth().oauth2(tokenFor("ana")).when().get("/api/orders").then().statusCode(200);

given().header("X-API-Key", "jh_test_k3x9q2_...").when().get("/api/orders").then().statusCode(200);

For a JWT protected API in tests, mint a token in the test with the same signing key the test configuration supplies to the application, or call the real login endpoint once in a @BeforeAll and reuse the token. Avoid hard coded long lived tokens committed to the repository. A test for the failure side is as important:

java
@Test
void aRequestWithoutCredentialsIsRejected() {
    given().when().get("/api/orders").then().statusCode(401);
}

@Test
void aUserCannotReadAnotherUsersOrder() {
    given().auth().oauth2(tokenFor("ben")).when().get("/api/orders/{id}", ordersOwnedByAna).then().statusCode(403);
}

Authorisation bugs are among the most serious API defects, and a table of (user, endpoint, expected status) cases, run as a parameterised test, catches them cheaply.

Specifications: share the boilerplate

Repeating the same headers and expectations in every test is noise. Build a RequestSpecification for the setup and a ResponseSpecification for common expectations once, and reuse them:

src/test/java/dev/javahacks/api/ApiSpecs.javajava
public final class ApiSpecs {
    private ApiSpecs() {}

    public static RequestSpecification request(int port) {
        return new RequestSpecBuilder()
                .setBaseUri("http://localhost")
                .setPort(port)
                .setBasePath("/api")
                .setContentType(ContentType.JSON)
                .setAccept(ContentType.JSON)
                .addHeader("X-Request-Id", UUID.randomUUID().toString())
                .log(LogDetail.ALL)
                .build();
    }

    public static ResponseSpecification ok() {
        return new ResponseSpecBuilder()
                .expectStatusCode(200)
                .expectContentType(ContentType.JSON)
                .expectResponseTime(lessThan(2000L), TimeUnit.MILLISECONDS)
                .build();
    }
}
java
given().spec(ApiSpecs.request(port))
.when().get("/orders/{id}", 1)
.then().spec(ApiSpecs.ok()).body("id", equalTo(1));

The test now says only what is particular to it. The response time expectation is a coarse guard against a gross regression, not a performance test: a shared CI machine makes tight timings flaky, so keep the bound generous and measure performance with a proper load testing tool and write the correctness checks here.

Validate the shape: JSON schema

Field by field assertions check what you thought of. A JSON schema describes the whole response shape, so an unexpected change, a renamed field, a type that became a string, a new null, fails the test. Put the schema in src/test/resources:

src/test/resources/schemas/order.jsonJSON
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "type": "object",
  "required": ["id", "customerEmail", "status", "lines"],
  "properties": {
    "id": {"type": "integer"},
    "customerEmail": {"type": "string", "format": "email"},
    "status": {"enum": ["NEW", "PAID", "SHIPPED", "CANCELLED"]},
    "lines": {
      "type": "array",
      "items": {
        "type": "object",
        "required": ["sku", "quantity"],
        "properties": {"sku": {"type": "string"}, "quantity": {"type": "integer", "minimum": 1}}
      }
    }
  },
  "additionalProperties": false
}
java
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;

given().when().get("/api/orders/1")
.then().statusCode(200).body(matchesJsonSchemaInClasspath("schemas/order.json"));

additionalProperties: false makes the schema strict: an extra field fails the test, which protects against accidentally exposing an internal field (a password hash, a database id) but also means adding a field requires updating the schema, a deliberate review step for a public API. If the schema comes from your OpenAPI document, even better: one source of truth, described in contract-first OpenAPI in Java.

Logging that helps

When a test fails you want to see the request and response. Logging everything on every test fills the build output. Log only on failure:

java
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();

or per request: .log().ifValidationFails() in given() and then(). A failing assertion then prints the request line, headers and body, and the response status, headers and body, immediately before the assertion error:

Text
Request method:	POST
Request URI:	http://localhost:53124/api/orders
Body:
{"customerEmail": "", "lines": []}

HTTP/1.1 400
Content-Type: application/problem+json

{"title":"Invalid request","status":400,"errors":[{"field":"customerEmail","message":"must not be blank"}]}

java.lang.AssertionError: 1 expectation failed.
Expected status code <201> but was <400>.

Reading this is usually faster than a debugger. The error message names the failed expectation and the actual value, and the response body usually says why.

Where REST Assured fits

REST Assured tests go over HTTP to a real server, so they exercise the servlet container, filters, serialisation, security and the database together. That makes them integration tests and slower than MockMvc, which dispatches in process. A reasonable division:

ToolStarts a serverBest for
MockMvc with @WebMvcTestNoController contracts, validation, error handlers, fast feedback
REST Assured on RANDOM_PORTYesEnd to end API behaviour, security, real serialisation, black box checks
PlaywrightYes, plus a browserCritical user journeys through the UI
Contract tests (Pact, Spring Cloud Contract)NoAgreements with consumers or providers across services

Many teams write the controller level detail with MockMvc, as in testing controllers with MockMvc, and keep a smaller REST Assured suite that runs against the whole application and, because it only needs a URL, against a deployed environment too: set RestAssured.baseURI from a system property and the same tests become a post deployment smoke test. In Quarkus, REST Assured is the built in approach for @QuarkusTest, which makes it a good habit across frameworks.

Pitfalls

Static configuration leaks. Global RestAssured.* fields persist across tests in a JVM; prefer specifications passed to each request, or reset in @AfterEach.

Deserialising with the production classes. A test that serialises the application's own DTOs cannot detect a breaking rename, since both sides change together. Use literal JSON for requests and assertions for responses.

Over asserting. Checking every field in every test makes tests brittle. Assert what the scenario is about, and rely on a schema test for shape.

Order dependent tests. Tests that rely on data created by earlier tests fail when run alone. Create the data each test needs.

Time and generated values. Ids and timestamps change on every run; use notNullValue(), matchesPattern or extract and reuse them.

Groovy version conflicts. REST Assured uses Groovy internally; a project with a different Groovy on the test classpath can see NoSuchMethodError. Align versions or exclude the transitive one.

When this does not apply

For reactive WebFlux applications, WebTestClient is the native equivalent and avoids a real port. If you test mostly through a front end, API tests still guard the contract beneath it. REST Assured is also not a load testing tool; use Gatling or k6 for that. References: the REST Assured usage guide and the Hamcrest matcher reference.

Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.