REST Assured for Java API Testing
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
- Write a GET test with status code and body assertions.
- Write a POST test with authentication and JSON body.
- Extract a value from the response (token) and reuse it.
- Create a request specification for reuse across tests.
- Challenge: Use JsonPath to validate a deeply nested JSON response.
FAQ
{{< faq "How do I validate XML responses?" "Use .body(\"path.to.element\", equalTo(\"value\")) with XMLPath syntax." >}}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