Wednesday, 11 February 2026

Rest Assured Chectsheet

REST Assured Cheat Sheet

🚀 REST Assured Cheat Sheet

Complete Reference for API Testing Interview Preparation

📦 Setup & Dependencies

Maven Dependency

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.3.0</version>
    <scope>test</scope>
</dependency>

Static Imports

import static io.restassured.RestAssured.*;
import static io.restassured.matcher.RestAssuredMatchers.*;
import static org.hamcrest.Matchers.*;

🎯 Basic Syntax

// Simple GET request
given()
    .when()
        .get("https://api.example.com/users")
    .then()
        .statusCode(200);

// BDD Style (Given-When-Then)
given()
    .header("Content-Type", "application/json")
.when()
    .post("/api/users")
.then()
    .statusCode(201);
💡 Tip: REST Assured follows BDD (Behavior Driven Development) style with Given-When-Then syntax for better readability.

⚙️ Configuration

// Base URI Configuration
RestAssured.baseURI = "https://api.example.com";
RestAssured.basePath = "/v1";
RestAssured.port = 8080;

// Request Specification
RequestSpecification requestSpec = new RequestSpecBuilder()
    .setBaseUri("https://api.example.com")
    .setContentType(ContentType.JSON)
    .build();

// Response Specification
ResponseSpecification responseSpec = new ResponseSpecBuilder()
    .expectStatusCode(200)
    .expectContentType(ContentType.JSON)
    .build();

📤 HTTP Methods

GET Request

get("/users")
get("/users/{id}", 123)

POST Request

post("/users")

PUT Request

put("/users/{id}", 123)

PATCH Request

patch("/users/{id}", 123)

DELETE Request

delete("/users/{id}", 123)

HEAD Request

head("/users")

📋 Request Parameters

Query Parameters

given()
    .queryParam("page", 1)
    .queryParam("limit", 10)
.when()
    .get("/users");

// Multiple params at once
given()
    .queryParams("page", 1, "limit", 10)
.when()
    .get("/users");

Path Parameters

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

// Multiple path params
given()
    .pathParams("userId", 1, "postId", 5)
.when()
    .get("/users/{userId}/posts/{postId}");

Form Parameters

given()
    .formParam("username", "john")
    .formParam("password", "secret")
.when()
    .post("/login");

📄 Request Body

JSON Body

// String JSON
String jsonBody = "{ \"name\": \"John\", \"email\": \"john@example.com\" }";
given()
    .contentType(ContentType.JSON)
    .body(jsonBody)
.when()
    .post("/users");

// Using POJO
User user = new User("John", "john@example.com");
given()
    .contentType(ContentType.JSON)
    .body(user)
.when()
    .post("/users");

// Using HashMap
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("name", "John");
jsonMap.put("email", "john@example.com");
given()
    .contentType(ContentType.JSON)
    .body(jsonMap)
.when()
    .post("/users");

XML Body

given()
    .contentType(ContentType.XML)
    .body("<user><name>John</name></user>")
.when()
    .post("/users");

📨 Headers & Cookies

// Single Header
given()
    .header("Authorization", "Bearer token123")
.when()
    .get("/users");

// Multiple Headers
given()
    .headers("Content-Type", "application/json", 
             "Accept", "application/json")
.when()
    .get("/users");

// Cookies
given()
    .cookie("session_id", "abc123")
.when()
    .get("/users");

✅ Response Validations

Status Code

then()
    .statusCode(200)
    .statusLine("HTTP/1.1 200 OK");

Response Body - JSON Path

then()
    .body("name", equalTo("John"))
    .body("age", greaterThan(18))
    .body("email", containsString("@example.com"))
    .body("data.size()", is(10))
    .body("data[0].id", notNullValue());

Array/List Validations

then()
    .body("users.size()", greaterThan(0))
    .body("users.name", hasItems("John", "Jane"))
    .body("users[0].name", equalTo("John"))
    .body("users.findAll{it.age > 18}.name", 
         hasItem("John"));

Headers Validation

then()
    .header("Content-Type", "application/json")
    .header("Server", containsString("nginx"));

Response Time

then()
    .time(lessThan(2000L), TimeUnit.MILLISECONDS);

🔍 Hamcrest Matchers

Matcher Description Example
equalTo() Exact match equalTo("John")
is() Syntactic sugar is(equalTo("John"))
not() Negation not(equalTo("John"))
hasItems() Contains items hasItems("a", "b")
hasItem() Contains item hasItem("a")
greaterThan() Greater than greaterThan(18)
lessThan() Less than lessThan(100)
containsString() String contains containsString("@")
startsWith() String starts with startsWith("http")
notNullValue() Not null notNullValue()
nullValue() Is null nullValue()
hasSize() Collection size hasSize(10)

🎭 Extract Response Data

// Extract as String
String name = get("/users/1").path("name");

// Extract with JsonPath
Response response = get("/users");
JsonPath jsonPath = response.jsonPath();
String firstName = jsonPath.getString("data[0].name");
List<String> names = jsonPath.getList("data.name");

// Extract entire response
Response response = given().get("/users");
String body = response.asString();
int statusCode = response.getStatusCode();
String header = response.getHeader("Content-Type");

// Deserialize to POJO
User user = get("/users/1").as(User.class);

🔐 Authentication Methods

Basic Authentication

given()
    .auth().basic("username", "password")
.when()
    .get("/secure/users");

Preemptive Basic Auth

given()
    .auth().preemptive().basic("username", "password")
.when()
    .get("/secure/users");

Digest Authentication

given()
    .auth().digest("username", "password")
.when()
    .get("/secure/users");

OAuth 2.0

given()
    .auth().oauth2("access_token_here")
.when()
    .get("/secure/users");

Bearer Token

given()
    .header("Authorization", "Bearer " + token)
.when()
    .get("/secure/users");

API Key

// In Header
given()
    .header("X-API-KEY", "your-api-key")
.when()
    .get("/api/data");

// In Query Param
given()
    .queryParam("api_key", "your-api-key")
.when()
    .get("/api/data");

🚀 Advanced Features

File Upload

// Single file
given()
    .multiPart(new File("file.txt"))
.when()
    .post("/upload");

// With control name
given()
    .multiPart("file", new File("data.json"), "application/json")
.when()
    .post("/upload");

File Download

byte[] data = get("/download/file.pdf").asByteArray();
InputStream stream = get("/download/file.pdf").asInputStream();

Request/Response Logging

// Log everything
given()
    .log().all()
.when()
    .get("/users")
.then()
    .log().all();

// Log specific parts
given()
    .log().headers()
    .log().body()
.when()
    .get("/users")
.then()
    .log().ifError()
    .log().ifValidationFails();

Filters

// Request/Response logging filter
given()
    .filter(new RequestLoggingFilter())
    .filter(new ResponseLoggingFilter())
.when()
    .get("/users");

// Custom filter
given()
    .filter((requestSpec, responseSpec, ctx) -> {
        // Custom logic here
        return ctx.next(requestSpec, responseSpec);
    })
.when()
    .get("/users");

Schema Validation

// JSON Schema validation
given()
.when()
    .get("/users")
.then()
    .assertThat()
    .body(matchesJsonSchemaInClasspath("user-schema.json"));

// XML Schema validation
then()
    .body(matchesXsdInClasspath("user-schema.xsd"));

Serialization/Deserialization

// POJO to JSON (Serialization)
User user = new User("John", "john@example.com");
given()
    .body(user)
.when()
    .post("/users");

// JSON to POJO (Deserialization)
User user = get("/users/1").as(User.class);

// List of POJOs
List<User> users = get("/users")
    .jsonPath()
    .getList(".", User.class);

⏱️ Timeouts & SSL

// Set timeout
given()
    .config(RestAssured.config()
        .httpClient(HttpClientConfig.httpClientConfig()
            .setParam("http.connection.timeout", 5000)
            .setParam("http.socket.timeout", 5000)))
.when()
    .get("/users");

// Ignore SSL certificate
given()
    .relaxedHTTPSValidation()
.when()
    .get("https://secure-api.com/users");

🔄 Reusable Specifications

// Create reusable request spec
RequestSpecification requestSpec = new RequestSpecBuilder()
    .setBaseUri("https://api.example.com")
    .setBasePath("/v1")
    .addHeader("Content-Type", "application/json")
    .addHeader("Authorization", "Bearer token")
    .build();

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

// Use them
given()
    .spec(requestSpec)
.when()
    .get("/users")
.then()
    .spec(responseSpec);

💼 Complete Examples

Example 1: CRUD Operations
@Test
public void testCRUDOperations() {
    // CREATE - POST
    String userId = given()
        .contentType(ContentType.JSON)
        .body("{ \"name\": \"John Doe\", \"email\": \"john@test.com\" }")
    .when()
        .post("/users")
    .then()
        .statusCode(201)
        .extract().path("id");

    // READ - GET
    given()
        .pathParam("id", userId)
    .when()
        .get("/users/{id}")
    .then()
        .statusCode(200)
        .body("name", equalTo("John Doe"));

    // UPDATE - PUT
    given()
        .pathParam("id", userId)
        .contentType(ContentType.JSON)
        .body("{ \"name\": \"Jane Doe\" }")
    .when()
        .put("/users/{id}")
    .then()
        .statusCode(200);

    // DELETE
    given()
        .pathParam("id", userId)
    .when()
        .delete("/users/{id}")
    .then()
        .statusCode(204);
}
Example 2: Data-Driven Testing
@DataProvider
public Object[][] getUserData() {
    return new Object[][] {
        {"John", "john@test.com", 201},
        {"Jane", "jane@test.com", 201},
        {"", "invalid", 400}
    };
}

@Test(dataProvider = "getUserData")
public void testUserCreation(String name, String email, int expectedStatus) {
    given()
        .contentType(ContentType.JSON)
        .body(String.format("{ \"name\": \"%s\", \"email\": \"%s\" }", name, email))
    .when()
        .post("/users")
    .then()
        .statusCode(expectedStatus);
}
Example 3: Chaining Requests
@Test
public void testChainedRequests() {
    // Step 1: Login and get token
    String token = given()
        .contentType(ContentType.JSON)
        .body("{ \"username\": \"admin\", \"password\": \"secret\" }")
    .when()
        .post("/login")
    .then()
        .statusCode(200)
        .extract().path("token");

    // Step 2: Use token to create user
    String userId = given()
        .header("Authorization", "Bearer " + token)
        .contentType(ContentType.JSON)
        .body("{ \"name\": \"Test User\" }")
    .when()
        .post("/users")
    .then()
        .statusCode(201)
        .extract().path("id");

    // Step 3: Verify user was created
    given()
        .header("Authorization", "Bearer " + token)
        .pathParam("id", userId)
    .when()
        .get("/users/{id}")
    .then()
        .statusCode(200)
        .body("name", equalTo("Test User"));
}
Example 4: TestNG Integration
public class ApiTests {
    
    @BeforeClass
    public void setup() {
        RestAssured.baseURI = "https://api.example.com";
        RestAssured.basePath = "/v1";
    }
    
    @Test(priority = 1)
    public void testGetUsers() {
        given()
            .log().all()
        .when()
            .get("/users")
        .then()
            .log().all()
            .statusCode(200);
    }
    
    @AfterClass
    public void tearDown() {
        RestAssured.reset();
    }
}

🎤 Common Interview Questions

Q1: What is REST Assured?

Answer: REST Assured is a Java library that provides a domain-specific language (DSL) for writing powerful, maintainable tests for RESTful APIs. It simplifies API testing by providing methods to make HTTP requests and validate responses using a BDD (Behavior Driven Development) style syntax.

Q2: Explain Given-When-Then syntax

Answer:

  • Given: Preconditions - setup like headers, authentication, request body, parameters
  • When: Action - the actual HTTP method call (GET, POST, PUT, DELETE)
  • Then: Assertions - validations on response like status code, headers, body
Q3: How do you handle authentication in REST Assured?

Answer: REST Assured supports multiple authentication methods:

  • Basic Auth: auth().basic(username, password)
  • Preemptive Basic: auth().preemptive().basic()
  • Digest Auth: auth().digest(username, password)
  • OAuth 2.0: auth().oauth2(token)
  • Bearer Token: header("Authorization", "Bearer " + token)
Q4: What is RequestSpecification and ResponseSpecification?

Answer: These are reusable specifications that help avoid code duplication:

  • RequestSpecification: Defines common request settings like base URI, headers, authentication that can be reused across multiple tests
  • ResponseSpecification: Defines common response validations like status code, content type that can be applied to multiple tests
Q5: How do you validate JSON response?

Answer: JSON validation can be done using:

  • JsonPath: body("data.name", equalTo("John"))
  • Root level: body("name", equalTo("John"))
  • Nested fields: body("user.address.city", equalTo("NYC"))
  • Arrays: body("users[0].name", equalTo("John"))
  • Size: body("users.size()", is(10))
Q6: Difference between path() and extract()?

Answer:

  • path(): Directly extracts value from response body. Example: get("/users").path("name")
  • extract(): Provides more options like extracting entire response, specific path, headers, cookies. Example: extract().path("name") or extract().response()
Q7: How to handle file upload in REST Assured?
given()
    .multiPart("file", new File("path/to/file.pdf"))
.when()
    .post("/upload");
Q8: What are Hamcrest matchers?

Answer: Hamcrest is a framework for writing matcher objects used in assertions. Common matchers include:

  • equalTo() - exact match
  • containsString() - substring match
  • hasItems() - collection contains items
  • greaterThan(), lessThan() - numeric comparison
  • notNullValue() - null check
Q9: How to perform JSON Schema validation?
given()
.when()
    .get("/users")
.then()
    .assertThat()
    .body(matchesJsonSchemaInClasspath("schema.json"));

This validates that the response structure matches the defined JSON schema.

Q10: How to measure response time?
// Assert response time
then()
    .time(lessThan(2000L), TimeUnit.MILLISECONDS);

// Extract response time
long responseTime = get("/users").time();
Q11: Explain Serialization and Deserialization

Answer:

  • Serialization: Converting Java object to JSON/XML format for request body. REST Assured automatically handles this when you pass POJO to body() method.
  • Deserialization: Converting JSON/XML response to Java object using as(Class) method.
Q12: How to handle cookies in REST Assured?
// Set cookie in request
given()
    .cookie("session_id", "abc123")
.when()
    .get("/users");

// Get cookie from response
String cookie = get("/login").getCookie("session_id");

🎯 Quick Tips for Interview

Always mention BDD style

REST Assured follows Given-When-Then pattern for better readability

Static imports are key

Mention the importance of static imports for clean syntax

Hamcrest matchers

Know common matchers like equalTo(), hasItems(), containsString()

Reusability

Talk about RequestSpec and ResponseSpec for code reusability

JSON Path

Understand JsonPath syntax for complex JSON validation

Logging

Mention log().all() for debugging and test reports

No comments:

Post a Comment

Rest Assured Chectsheet

REST Assured Cheat Sheet 🚀 REST Assured Cheat Sheet Complete Reference for ...