REST Assured Cheat Sheet 

Everything you use daily in REST Assured on one page — for writing tests and for revising before an interview. New to REST Assured? Start with The Complete REST Assured Tutorial. See also: Logging & Response Extraction in REST Assured.

Advertisement

Project Setup

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.5.0</version>          <!-- use the latest 5.x -->
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>json-schema-validator</artifactId>   <!-- only for schema validation -->
    <version>5.5.0</version>
    <scope>test</scope>
</dependency>

<!-- Plus TestNG or JUnit, and Jackson (jackson-databind) for POJOs.
     JsonPath and XmlPath come with rest-assured automatically. -->

Static imports

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;

Given–When–Then ⭐

Block Purpose
given() Set up the request — base URI, headers, auth, parameters, body
when() Send it — the HTTP method and endpoint
then() Validate the response — status, body, headers, time
given()
    .baseUri("https://api.example.com")
    .contentType(ContentType.JSON)
    .body(payload)
.when()
    .post("/users")
.then()
    .statusCode(201)
    .body("name", equalTo("Nav"));

Building Requests

HTTP methods

.when().get("/users")
.when().post("/users")
.when().put("/users/1")
.when().patch("/users/1")
.when().delete("/users/1")

Parameters

given().queryParam("limit", 10).queryParam("skip", 5)          // ?limit=10&skip=5

given().pathParam("id", 123)
    .when().get("/users/{id}")                                 // /users/123

given().formParam("username", "admin")                         // form-encoded body

Headers, cookies and content types

given().header("Authorization", "Bearer " + token)

given().headers(headerMap)

given().cookie("session", value)

given().contentType(ContentType.JSON)

given().accept(ContentType.JSON)

Request body

given().body(jsonString)                          // raw JSON string

given().body(Map.of("name", "Nav", "job", "QA"))  // Map → JSON

given().body(pojoObject)                          // POJO → JSON (needs Jackson or Gson)

given().body(new File("src/test/resources/user.json"))

File upload (multipart)

given()
    .multiPart("file", new File("src/test/resources/resume.pdf"))
    .when()
    .post("/upload")
    .then()
    .statusCode(200);

Global settings

RestAssured.baseURI = "https://api.example.com";   // default for every request

given().relaxedHTTPSValidation()                   // test environments with self-signed certificates

Response Validation

.then()
    .statusCode(200)
    .statusLine(containsString("OK"))
    .contentType(ContentType.JSON)
    .header("Content-Type", containsString("application/json"))
    .cookie("session", notNullValue())
    .body("id", equalTo(101))
    .body("name", notNullValue())
    .body("users.size()", equalTo(5))
    .body("users.name", hasItems("Nav", "Alex"))
    .time(lessThan(2000L));                  // milliseconds

Hamcrest matchers

Matcher Checks
equalTo() / not(equalTo()) Exact value / negation
containsString(), startsWith() Text content
hasItem() / hasItems() Array contains values
hasSize(), empty() Collection size
hasKey() Object has a field
notNullValue() / nullValue() Null checks
greaterThan() / lessThan() Numeric comparison
everyItem() Every element matches
anyOf() / allOf() Combine matchers

GPath: nested JSON and arrays

.body("data.address.city", equalTo("Pune"))                              // nested object

.body("data.orders[0].id", equalTo(101))                                 // first array item

.body("data.orders.find { it.status == 'SHIPPED' }.id", equalTo(102))    // first match

.body("data.orders.findAll { it.amount > 100 }.size()", equalTo(2))      // all matches

.body("data.orders.amount.sum()", equalTo(750))                          // aggregate

Extraction & JsonPath ⭐

// One value
String token = given()
    .body(credentials)
    .when()
    .post("/login")
    .then()
    .statusCode(200)
    .extract()
    .path("token");

// The whole response
Response response = when()
    .get("/users")
    .then()
    .extract()
    .response();

int id = response.path("users[0].id");

String name = response.jsonPath().getString("users[0].name");

List<String> names = response.jsonPath().getList("users.name");

String raw = response.asString();

API chaining

int userId = given()
    .contentType(ContentType.JSON)
    .body(newUser)
    .when()
    .post("/users")
    .then()
    .statusCode(201)
    .extract()
    .path("id");

given()
    .pathParam("id", userId)
    .when()
    .get("/users/{id}")
    .then()
    .statusCode(200);

Logging

given().log().all()                 // log the request

.then().log().all()                 // log the response

.then().log().body()

.then().log().ifValidationFails()   // ⭐ log only when an assertion fails

Authentication

given().auth().preemptive().basic("user", "password")   // basic — sends credentials immediately

given().auth().basic("user", "password")                // basic — waits for a 401 challenge

given().auth().oauth2(accessToken)                      // OAuth 2.0 bearer token

given().header("Authorization", "Bearer " + token)      // bearer / JWT

given().header("x-api-key", apiKey)                     // API key

More: Authentication in REST Assured.

Serialization (POJOs)

// Java object → JSON request
User user = new User("Nav", "nav@example.com");

given()
    .contentType(ContentType.JSON)
    .body(user)
    .when()
    .post("/users");

// JSON response → Java object
User created = when()
    .get("/users/1")
    .then()
    .extract()
    .as(User.class);

POJOs need a no-argument constructor and getters (or public fields). More: Serialization & POJO.

JSON Schema Validation

.then()
    .body(matchesJsonSchemaInClasspath("schemas/user-schema.json"));   // file in src/test/resources/schemas/

Catches missing fields, wrong data types and contract changes. More: JSON Schema Validation. A closely related topic: Response Validation in REST Assured.

Framework Patterns ⭐

RequestSpecification requestSpec = new RequestSpecBuilder()
        .setBaseUri(System.getProperty("baseUri", "https://api.example.com"))
        .setContentType(ContentType.JSON)
        .addHeader("Authorization", "Bearer " + token)
        .build();

ResponseSpecification okJson = new ResponseSpecBuilder()
        .expectStatusCode(200)
        .expectContentType(ContentType.JSON)
        .expectResponseTime(lessThan(2000L))
        .build();

given()
    .spec(requestSpec)
    .when()
    .get("/users")
    .then()
    .spec(okJson);

Specifications remove repeated setup and checks, and reading baseUri from a system property lets the same tests run on any environment (mvn test -DbaseUri=https://qa.example.com). More: REST Assured Framework Design.

Go Deeper

📚 Official documentation: REST Assured official site · MDN: HTTP