Skip to content

REST Assured for Java API Testing

DodaTech Updated 2026-06-28 3 min read

In this tutorial, you will learn about REST Assured for Java API Testing. We cover key concepts, practical examples, and best practices to help you master this topic.

REST Assured is a Java DSL for testing REST APIs. Its fluent given/when/then syntax makes tests readable and maintainable. It supports JSON and XML validation, authentication, specifications, and integrates with JUnit and TestNG.

What You'll Learn

  • REST Assured given/when/then syntax
  • JSON and XML response validation
  • Authentication and specification reuse
  • Parameterized requests
  • Integration with JUnit 5

Why It Matters

REST Assured is the de facto standard for Java API testing. It simplifies complex HTTP testing scenarios with a readable DSL. Its JSON Path and XML Path support validate nested response structures.

Real-World Use

Spring Boot documentation uses REST Assured in examples. Many Java Microservices projects use REST Assured for integration tests. It is commonly paired with Spring Boot Test and Testcontainers.

flowchart LR
    Test[JUnit Test] --> Given[given(): Setup]
    Given --> Auth[Authentication]
    Given --> Headers[Headers]
    Given --> Params[Query Params]
    Given --> Body[Request Body]
    Given --> When[when(): Execute]
    When --> Request[HTTP Request]
    Request --> Then[then(): Assert]
    Then --> Status[Status Code]
    Then --> Body[Body Validation]
    Then --> Headers[Response Headers]

Teacher Mindset

REST Assured tests read like sentences: "Given this setup, when I make this request, then expect this response." Use specifications to avoid repeating configuration. Use JsonPath for precise body assertions.

Code Examples

// Example 1: Basic REST Assured test
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

@Test
public void testGetUsers() {
    given()
        .baseUri("http://api.example.com")
        .header("Accept", "application/json")
    .when()
        .get("/api/users")
    .then()
        .statusCode(200)
        .body("size()", greaterThan(0))
        .body("[0].name", notNullValue());
}
// Example 2: Authentication and request body
@Test
public void testCreateUser() {
    String token = given()
        .body("{\"username\":\"admin\",\"password\":\"secret\"}")
        .post("/auth/login")
        .path("token");

    given()
        .auth().oauth2(token)
        .contentType(ContentType.JSON)
        .body("{\"name\":\"Alice\",\"email\":\"alice@test.com\"}")
    .when()
        .post("/api/users")
    .then()
        .statusCode(201)
        .body("name", equalTo("Alice"))
        .body("id", notNullValue());
}
// Example 3: Specifications and logging
public class UserApiTest {
    private static RequestSpecification requestSpec;

    @BeforeAll
    public static void setup() {
        requestSpec = new RequestSpecBuilder()
            .setBaseUri("http://api.example.com")
            .setContentType(ContentType.JSON)
            .addHeader("Authorization", "Bearer " + getToken())
            .log(LogDetail.ALL)
            .build();
    }

    @Test
    public void testUpdateUser() {
        given()
            .spec(requestSpec)
            .body("{\"name\":\"Alice Updated\"}")
            .pathParam("id", 1)
        .when()
            .put("/api/users/{id}")
        .then()
            .statusCode(200)
            .body("name", equalTo("Alice Updated"))
            .body("updatedAt", notNullValue());
    }
}

Common Mistakes

  • Not using request specifications for shared configuration
  • Forgetting to import static methods (given, when, then)
  • Using string concatenation for JSON bodies instead of JSON objects
  • Not logging requests and responses for test debugging
  • Hardcoding endpoints without base URI configuration

Practice

  1. Write a GET test with status code and body assertions.
  2. Write a POST test with authentication and JSON body.
  3. Extract a value from the response (token) and reuse it.
  4. Create a request specification for reuse across tests.
  5. Challenge: Use JsonPath to validate a deeply nested JSON response.

FAQ

What is the difference between REST Assured and Postman?

REST Assured is a Java library for code-based API testing. Postman is a GUI tool. REST Assured integrates with JUnit in CI/CD.

Can REST Assured test GraphQL?

Yes. Send GraphQL queries as POST requests with the query in the body.

{{< faq "How do I validate XML responses?" "Use .body(\"path.to.element\", equalTo(\"value\")) with XMLPath syntax." >}}
Does REST Assured support OAuth2?

Yes. Use .auth().oauth2(token) for OAuth2 authentication.

Can I use REST Assured with Spring Boot?

Yes. REST Assured works well with Spring Boot Test. Use @SpringBootTest with a random port.

Mini Project

Write a REST Assured test suite for a REST API with: request specification for shared config, CRUD tests, JSON body validation, authentication flow, and parameterized path parameters.

What's Next

Next, you will learn about Contract Testing with Pact and schema validation.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro