Automate API Tests with REST Assured (Java)
REST Assured is the most used Java library for API test automation. Tests read almost like plain English: given this request, when I call the endpoint, then the response should be this.
Setup
Use the same Maven project as the Selenium setup lesson and add:
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.5.0</version>
<scope>test</scope>
</dependency>
Your first GET test
import io.restassured.RestAssured;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class UsersApiTest {
@BeforeClass
public void setUp() {
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
}
@Test
public void getUserReturnsTheRightUser() {
given()
.when()
.get("/users/1")
.then()
.statusCode(200)
.contentType("application/json")
.body("id", equalTo(1))
.body("email", containsString("@"))
.body("address.city", notNullValue())
.time(lessThan(2000L));
}
}
Paths like address.city read nested JSON. Matchers such as equalTo, containsString and hasSize come from Hamcrest.
POST with a body
@Test
public void createPostReturns201() {
String body = """
{ "title": "Hello", "body": "First post", "userId": 1 }
""";
given()
.contentType("application/json")
.body(body)
.when()
.post("/posts")
.then()
.statusCode(201)
.body("id", notNullValue())
.body("title", equalTo("Hello"));
}
Text blocks (""") need Java 15 or newer. For bigger bodies, create a Java class (a POJO) and pass the object to body(). REST Assured turns it into JSON when Jackson is on the classpath.
Read values from the response
int id = given()
.contentType("application/json")
.body(body)
.when()
.post("/posts")
.then()
.statusCode(201)
.extract().path("id");
Use extracted values to chain calls, like reading a token from /auth/login and sending it in the next request.
A negative test
@Test
public void unknownUserReturns404() {
given()
.when()
.get("/users/99999")
.then()
.statusCode(404);
}
Sending a token
given()
.auth().oauth2(token) // adds Authorization: Bearer <token>
.queryParam("status", "confirmed")
.when()
.get("/bookings")
.then()
.statusCode(200)
.body("data", everyItem(hasEntry("status", "confirmed")));
Check the whole shape with a JSON schema
Add the json-schema-validator dependency from REST Assured, save a schema in src/test/resources/schemas/user.json, then:
.then()
.body(matchesJsonSchemaInClasspath("schemas/user.json"));
One line checks every field name and type, so you notice when developers change the API by accident.
Log only when something fails
given()
.log().ifValidationFails()
.when()
.get("/users/1")
.then()
.log().ifValidationFails()
.statusCode(200);