API Testing · Automating API Tests

Automate API Tests with REST Assured (Java)

Lesson 6 of 7 · 12 min read

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);
Practice: automate the six test cases from the API checklist lesson. Some will fail against JSONPlaceholder because it is a fake API. Write down why, as you would in a real bug report.
All 7 lessons in API Testing
  1. What Is API Testing?
  2. HTTP Basics for Testers: Methods, Status Codes, Headers
  3. API Testing with Postman, Step by Step
  4. What to Test in an API: A Complete Checklist
  5. Testing API Authentication: API Keys, Tokens and OAuth
  6. Automate API Tests with REST Assured (Java)
  7. API Test Framework Structure and CI