Skip to content

REST Assured Cheatsheet

Installation

Maven Installation (pom.xml)

<dependencies>
    <!-- Core REST Assured -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>5.4.0</version>
        <scope>test</scope>
    </dependency>

    <!-- JSON Schema Validation -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>json-schema-validator</artifactId>
        <version>5.4.0</version>
        <scope>test</scope>
    </dependency>

    <!-- JSON Path -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>json-path</artifactId>
        <version>5.4.0</version>
    </dependency>

    <!-- XML Path -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>xml-path</artifactId>
        <version>5.4.0</version>
    </dependency>
</dependencies>

Gradle Installation (build.gradle)

dependencies {
    testImplementation 'io.rest-assured:rest-assured:5.4.0'
    testImplementation 'io.rest-assured:json-schema-validator:5.4.0'
    testImplementation 'io.rest-assured:json-path:5.4.0'
    testImplementation 'io.rest-assured:xml-path:5.4.0'
}

Platform-Specific Prerequisites

Platform Installation Command
Ubuntu/Debian sudo apt update && sudo apt install openjdk-11-jdk maven -y
macOS brew install openjdk@11 maven
Windows choco install openjdk11 maven -y (using Chocolatey)
Verify Java java -version
Verify Maven mvn -version

Required Imports

// Static imports for fluent API
import static io.rest-assured.RestAssured.*;
import static io.rest-assured.matcher.RestAssuredMatchers.*;
import static org.hamcrest.Matchers.*;

// Additional imports
import io.rest-assured.response.Response;
import io.rest-assured.specification.RequestSpecification;
import io.rest-assured.http.ContentType;

Basic HTTP Methods

Command Description
given().when().get("url") Execute GET request
given().when().post("url") Execute POST request
given().when().put("url") Execute PUT request
given().when().patch("url") Execute PATCH request
given().when().delete("url") Execute DELETE request
given().when().head("url") Execute HEAD request
given().when().options("url") Execute OPTIONS request
get("url") Shorthand GET without given/when
post("url") Shorthand POST without given/when
delete("url") Shorthand DELETE without given/when

Request Specification

Command Description
given().baseUri("url") Set base URI for requests
given().basePath("/api/v1") Set base path for all endpoints
given().port(8080) Set port number
given().contentType(ContentType.JSON) Set Content-Type header
given().accept(ContentType.JSON) Set Accept header
given().header("key", "value") Add single header
given().headers(map) Add multiple headers from map
given().cookie("name", "value") Add cookie
given().queryParam("key", "value") Add query parameter
given().queryParams(map) Add multiple query parameters
given().pathParam("key", "value") Add path parameter
given().formParam("key", "value") Add form parameter
given().body(object) Set request body (auto-serialized)
given().body("json string") Set raw JSON/XML body
given().multiPart(file) Add multipart file upload

Response Validation

Command Description
.then().statusCode(200) Assert HTTP status code
.then().statusLine("HTTP/1.1 200 OK") Assert full status line
.then().contentType(ContentType.JSON) Assert response content type
.then().header("key", "value") Assert header value
.then().body("field", equalTo(value)) Assert JSON field equals value
.then().body("field", notNullValue()) Assert field is not null
.then().body("field", hasSize(5)) Assert array/list size
.then().body("field", hasItems("a", "b")) Assert array contains items
.then().body("field", containsString("text")) Assert string contains text
.then().body("field", greaterThan(10)) Assert numeric comparison
.then().body("field", matchesPattern("regex")) Assert regex match
.then().time(lessThan(2000L)) Assert response time < 2000ms
.then().assertThat() Explicit assertion mode
.then().log().all() Log entire response
.then().log().ifError() Log only on error

JSON Path Validation

Command Description
.body("user.name", equalTo("John")) Validate nested field
.body("users[0].name", equalTo("John")) Validate array element
.body("users.name", hasItems("John")) Validate array field values
.body("users.size()", is(5)) Validate array size
.body("users.findAll{it.age > 18}", hasSize(3)) Filter with Groovy closure
.body("users.find{it.id == 1}.name", equalTo("John")) Find specific element
.body("$.store.book[0].title", equalTo("Book")) JsonPath expression
.body("users*.name", hasItems("John")) Spread operator for collections
.body("'user.name'", equalTo("John")) Escape field with dots
.body("users.collect{it.name}", hasItems("John")) Transform collection

Response Extraction

Command Description
.extract().response() Extract full Response object
.extract().asString() Extract response as String
.extract().path("field") Extract specific field value
.extract().jsonPath() Get JsonPath object
.extract().xmlPath() Get XmlPath object
.extract().as(Class.class) Deserialize to object
.extract().statusCode() Extract status code
.extract().header("key") Extract header value
.extract().cookie("name") Extract cookie value
.extract().time() Extract response time

Advanced Authentication

Command Description
given().auth().basic("user", "pass") HTTP Basic authentication
given().auth().digest("user", "pass") HTTP Digest authentication
given().auth().form("user", "pass") Form-based authentication
given().auth().oauth2("token") OAuth 2.0 Bearer token
given().auth().preemptive().basic("user", "pass") Preemptive Basic auth
given().auth().none() Explicitly no authentication
given().header("Authorization", "Bearer token") Manual Bearer token
given().header("Authorization", "ApiKey key") Custom API key auth

Request Specifications (Reusable)

// Create reusable specification
RequestSpecification requestSpec = new RequestSpecBuilder()
    .setBaseUri("https://api.example.com")
    .setBasePath("/v1")
    .addHeader("Authorization", "Bearer token")
    .setContentType(ContentType.JSON)
    .build();

// Use specification
given()
    .spec(requestSpec)
    .when()
    .get("/users");
Command Description
new RequestSpecBuilder() Create request specification builder
.setBaseUri("url") Set base URI in spec
.setBasePath("path") Set base path in spec
.addHeader("key", "value") Add header to spec
.setContentType(type) Set content type in spec
.addQueryParam("key", "value") Add query param to spec
.setAuth(authScheme) Set authentication in spec
.build() Build the specification
given().spec(requestSpec) Apply specification to request

Response Specifications (Reusable)

// Create reusable response specification
ResponseSpecification responseSpec = new ResponseSpecBuilder()
    .expectStatusCode(200)
    .expectContentType(ContentType.JSON)
    .expectResponseTime(lessThan(2000L))
    .build();

// Use specification
given()
    .when()
    .get("/users")
    .then()
    .spec(responseSpec);
Command Description
new ResponseSpecBuilder() Create response specification builder
.expectStatusCode(code) Expect status code in spec
.expectContentType(type) Expect content type in spec
.expectHeader("key", "value") Expect header in spec
.expectResponseTime(matcher) Expect response time constraint
.expectBody("field", matcher) Expect body validation
.build() Build the specification
.then().spec(responseSpec) Apply specification to response

Logging

Command Description
given().log().all() Log all request details
given().log().body() Log request body only
given().log().headers() Log request headers only
given().log().cookies() Log request cookies only
given().log().params() Log request parameters only
given().log().method() Log HTTP method only
given().log().uri() Log request URI only
given().log().ifValidationFails() Log request if validation fails
.then().log().all() Log all response details
.then().log().body() Log response body only
.then().log().headers() Log response headers only
.then().log().status() Log response status only
.then().log().ifError() Log response only on error
.then().log().ifStatusCodeIsEqualTo(code) Conditional logging by status
.then().log().ifStatusCodeMatches(matcher) Conditional logging by matcher

JSON Schema Validation

import static io.rest-assured.module.jsv.JsonSchemaValidator.*;

// Validate against JSON schema
given()
    .when()
    .get("/users/1")
    .then()
    .assertThat()
    .body(matchesJsonSchemaInClasspath("user-schema.json"));
Command Description
matchesJsonSchemaInClasspath("schema.json") Validate against schema in classpath
matchesJsonSchema(new File("schema.json")) Validate against schema file
matchesJsonSchema("schema string") Validate against schema string
JsonSchemaValidator.matchesJsonSchemaInClasspath() Static import for validation

XML Path Validation

Command Description
.body("user.name", equalTo("John")) Validate XML element
.body("user.@id", equalTo("123")) Validate XML attribute
.body("users.user.size()", is(5)) Validate XML list size
.body("users.user[0].name", equalTo("John")) Validate XML list element
.body(hasXPath("/user/name", equalTo("John"))) XPath validation
.body(hasXPath("//user[@id='123']")) XPath existence check

Multipart/Form Data

// File upload
given()
    .multiPart("file", new File("test.pdf"))
    .multiPart("description", "Test file")
    .when()
    .post("/upload");

// Multiple files
given()
    .multiPart("file1", new File("test1.pdf"))
    .multiPart("file2", new File("test2.pdf"))
    .when()
    .post("/upload");
Command Description
.multiPart("name", file) Upload file
.multiPart("name", file, "mime/type") Upload file with MIME type
.multiPart("name", "value") Add text multipart field
.multiPart("name", bytes, "filename") Upload byte array
.formParam("key", "value") Add form parameter
.formParams(map) Add multiple form parameters

Filters (Request/Response Interceptors)

// Custom filter
given()
    .filter(new Filter() {
        public Response filter(FilterableRequestSpecification requestSpec,
                             FilterableResponseSpecification responseSpec,
                             FilterContext ctx) {
            // Modify request/response
            return ctx.next(requestSpec, responseSpec);
        }
    })
    .when()
    .get("/users");
Command Description
.filter(filter) Add custom filter
.filter(new RequestLoggingFilter()) Add request logging filter
.filter(new ResponseLoggingFilter()) Add response logging filter
.filter(new ErrorLoggingFilter()) Add error logging filter
.filters(filter1, filter2) Add multiple filters

Configuration

Global Configuration

// Set global configuration
RestAssured.baseURI = "https://api.example.com";
RestAssured.basePath = "/v1";
RestAssured.port = 443;
RestAssured.authentication = basic("user", "pass");
RestAssured.defaultParser = Parser.JSON;
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();

// Reset to defaults
RestAssured.reset();
Configuration Description
RestAssured.baseURI Set default base URI
RestAssured.basePath Set default base path
RestAssured.port Set default port
RestAssured.authentication Set default authentication
RestAssured.defaultParser Set default response parser
RestAssured.requestSpecification Set default request spec
RestAssured.responseSpecification Set default response spec
RestAssured.filters() Add global filters
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails() Auto-log on failure
RestAssured.useRelaxedHTTPSValidation() Disable SSL validation
RestAssured.reset() Reset all configurations

SSL/TLS Configuration

// Relaxed HTTPS validation (testing only)
given()
    .relaxedHTTPSValidation()
    .when()
    .get("https://api.example.com");

// Custom keystore
given()
    .keyStore("/path/to/keystore.jks", "password")
    .when()
    .get("https://api.example.com");

// Custom truststore
given()
    .trustStore("/path/to/truststore.jks", "password")
    .when()
    .get("https://api.example.com");
Command Description
.relaxedHTTPSValidation() Disable SSL certificate validation
.keyStore(path, password) Set client keystore
.trustStore(path, password) Set truststore
.keyStore(file, password) Set keystore from File object
RestAssured.useRelaxedHTTPSValidation() Global relaxed HTTPS

Common Use Cases

Use Case 1: Simple GET Request with Validation

import static io.rest-assured.RestAssured.*;
import static org.hamcrest.Matchers.*;

@Test
public void testGetUser() {
    given()
        .pathParam("id", 1)
    .when()
        .get("https://jsonplaceholder.typicode.com/users/{id}")
    .then()
        .statusCode(200)
        .contentType(ContentType.JSON)
        .body("id", equalTo(1))
        .body("name", notNullValue())
        .body("email", containsString("@"));
}

Use Case 2: POST Request with JSON Body and Extraction

@Test
public void testCreateUser() {
    // Create user object
    Map<String, String> user = new HashMap<>();
    user.put("name", "John Doe");
    user.put("email", "john@example.com");

    // Send POST and extract ID
    int userId = given()
        .contentType(ContentType.JSON)
        .body(user)
    .when()
        .post("https://api.example.com/users")
    .then()
        .statusCode(201)
        .body("name", equalTo("John Doe"))
        .body("email", equalTo("john@example.com"))
    .extract()
        .path("id");

    System.out.println("Created user ID: " + userId);
}

Use Case 3: Authentication and Reusable Specifications

public class ApiTest {
    private static RequestSpecification requestSpec;
    private static ResponseSpecification responseSpec;

    @BeforeClass
    public static void setup() {
        // Reusable request specification
        requestSpec = new RequestSpecBuilder()
            .setBaseUri("https://api.example.com")
            .setBasePath("/v1")
            .addHeader("Authorization", "Bearer " + getToken())
            .setContentType(ContentType.JSON)
            .build();

        // Reusable response specification
        responseSpec = new ResponseSpecBuilder()
            .expectContentType(ContentType.JSON)
            .expectResponseTime(lessThan(2000L))
            .build();
    }

    @Test
    public void testGetUsers() {
        given()
            .spec(requestSpec)
            .queryParam("page", 1)
        .when()
            .get("/users")
        .then()
            .spec(responseSpec)
            .statusCode(200)
            .body("data.size()", greaterThan(0));
    }

    private static String getToken() {
        return given()
            .contentType(ContentType.JSON)
            .body("{\"username\":\"admin\",\"password\":\"secret\"}")
        .when()
            .post("https://api.example.com/auth/login")
        .then()
            .statusCode(200)
        .extract()
            .path("token");
    }
}

Use Case 4: File Upload with Multipart

@Test
public void testFileUpload() {
    File file = new File("src/test/resources/test-document.pdf");

    given()
        .multiPart("file", file, "application/pdf")
        .multiPart("description", "Test document")
        .multiPart("category", "reports")
    .when()
        .post("https://api.example.com/upload")
    .then()
        .statusCode(200)
        .body("filename", equalTo("test-document.pdf"))
        .body("size", greaterThan(0))
        .body("status", equalTo("uploaded"));
}

Use Case 5: Complex JSON Validation with JsonPath

@Test
public void testComplexJsonValidation() {
    given()
        .queryParam("page", 1)
    .when()
        .get("https://api.example.com/products")
    .then()
        .statusCode(200)
        // Validate array size
        .body("products.size()", equalTo(10))
        // Validate nested fields
        .body("products[0].name", notNullValue())
        .body("products[0].price.amount", greaterThan(0f))
        .body("products[0].price.currency", equalTo("USD"))
        // Validate all items in array
        .body("products.findAll { it.price.amount > 100 }.size()", greaterThan(0))
        // Validate specific item
        .body("products.find { it.id == 'PROD-123' }.name", equalTo("Widget"))
        // Validate collection properties
        .body("products*.category", hasItems("Electronics", "Books"));
}

Use Case 6: Response Deserialization to POJO

// User POJO class
public class User {
    private int id;
    private String name;
    private String email;
    // Getters and setters
}

@Test
public void testResponseDeserialization() {
    // Extract as single object
    User user = given()
        .pathParam("id", 1)
    .when()
        .get("https://api.example.com/users/{id}")
    .then()
        .statusCode(200)
    .extract()
        .as(User.class);

    Assert.assertEquals(1, user.getId());
    Assert.assertNotNull(user.getName());

    // Extract as list of objects
    List<User> users = given()
    .when()
        .get("https://api.example.com/users")
    .then()
        .statusCode(200)
    .extract()
        .jsonPath()
        .getList("data", User.class);

    Assert.assertTrue(users.size() > 0);
}

Use Case 7: JSON Schema Validation

// user-schema.json in src/test/resources
/*
{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "id": {"type": "integer"},
    "name": {"type": "string"},
    "email": {"type": "string", "format": "email"}
  },
  "required": ["id", "name", "email"]
}
*/

@Test
public void testJsonSchemaValidation() {
    given()
        .pathParam("id", 1)
    .when()
        .get("https://api.example.com/users/{id}")
    .then()
        .statusCode(200)
        .assertThat()
        .body(matchesJsonSchemaInClasspath("user-schema.json"));
}

Best Practices

  1. Use Static Imports for Readability
  2. Import io.rest-assured.RestAssured.* and org.hamcrest.Matchers.* statically for cleaner, more readable test code
  3. The Given-When-Then syntax becomes more natural and BDD-like