
REST Assured Interview Questions: The Complete Guide for 2026(Beginner to Architect Level)
REST Assured Interview Questions are the single most important topic you need to master if you are preparing for any QA automation, SDET, Test Lead, or Automation Architect role in 2026. Every serious API automation interview includes REST Assured Interview Questions โ not because it is a buzzword, but because REST Assured has become the industry standard for API testing in the Java ecosystem.
This is not another generic list. This guide covers 40+ REST Assured Interview Questions with detailed explanations, real production-grade code examples, and interview-focused takeaways โ structured from absolute beginner to architect level. Whether you are appearing for your first automation role or targeting a senior SDET position at a product company, these REST Assured Interview Questions will prepare you for every round.
What makes this guide different from every other REST Assured Interview Questions resource you have read:
- Every answer is written the way you should speak it in an actual interview โ not as a textbook definition
- Every code snippet is copy-paste ready and tested against real public APIs
- Questions are grouped by difficulty so you can track your progress
- Senior-level REST Assured Interview Questions cover framework design, CI/CD, and architecture โ areas most guides completely ignore
By the end of this guide, you will be able to answer any REST Assured Interview Question thrown at you โ from “What is REST Assured?” all the way to “How do you design a scalable API testing framework with REST Assured?”
Table of Contents
- Why REST Assured Interview Questions Matter in 2026
- REST Assured Fundamentals โ What Every Interview Starts With
- REST Assured Interview Questions 1โ20 โ Beginner Level
- REST Assured Interview Questions 21โ40 โ Intermediate Level
- REST Assured Interview Questions 41โ60 โ Advanced Level
- REST Assured Interview Questions 61โ80 โ Architect & Framework Design Level
- REST Assured Interview Questions on Authentication
- REST Assured Interview Questions on Framework Integration
- REST Assured Interview Questions โ Scenario Based
- How to Answer REST Assured Interview Questions Like a Senior Engineer
- REST Assured vs Other API Testing Tools โ Interview Comparison
- Common Mistakes Candidates Make in REST Assured Interviews
- REST Assured Interview Questions โ Quick Revision Cheat Sheet
- What to Learn After These REST Assured Interview Questions
1. Why REST Assured Interview Questions Matter in 2026
Before diving into the REST Assured Interview Questions themselves, let us understand why this topic dominates automation interviews in 2026.
API testing has shifted from being a “nice to have” skill to a core mandatory requirement for every QA automation role. Modern applications are built on microservices architectures where hundreds of APIs communicate with each other constantly. A QA engineer who cannot test APIs is operating at half capacity โ and hiring managers know it.
REST Assured Interview Questions are designed to test three distinct things simultaneously:
Conceptual clarity โ Do you understand what you are doing and why? An interviewer asking “What is the difference between queryParam and pathParam?” is not just asking about syntax. They want to know if you understand how URLs are structured and why different parameter types exist.
Hands-on coding ability โ Can you write REST Assured test code without looking at documentation? REST Assured Interview Questions almost always include a live coding component where you are asked to write a test from scratch. Knowing the API by heart is non-negotiable.
Framework thinking โ Can you scale REST Assured beyond individual tests into a maintainable, reusable framework? Senior REST Assured Interview Questions focus almost entirely on this โ RequestSpecification, ResponseSpecification, base configurations, data-driven approaches, and CI/CD integration.
The QA automation job market in India in 2026 is highly competitive. Companies like Infosys, TCS, Wipro, Cognizant, and every major product company hiring in Pune, Bangalore, Hyderabad, and Chennai include REST Assured Interview Questions as a standard filter. Candidates who have genuinely mastered REST Assured Interview Questions clear technical rounds that eliminate 70% of other applicants.
2. REST Assured Fundamentals โ What Every Interview Starts With
Before you tackle any REST Assured Interview Questions, you must have these fundamentals locked in your memory. Interviewers use these as warm-up questions to gauge your baseline โ and a weak answer here signals a weak candidate before the real questions even begin.
What is REST Assured?
REST Assured is an open-source Java-based library for testing and validating RESTful web services. It was created by Johan Haleby and is currently maintained by the REST Assured community on GitHub. REST Assured simplifies HTTP communication by providing a domain-specific language (DSL) that is both readable and powerful.
The core philosophy of REST Assured is to make API testing feel as natural and readable as writing plain English. The BDD-style syntax โ given(), when(), then() โ mirrors the Gherkin language used in Cucumber, making REST Assured tests self-documenting.
Why is REST Assured the Industry Standard?
REST Assured became the dominant API testing library in the Java ecosystem for several practical reasons:
- It requires zero boilerplate for common operations โ a complete GET request with validation is three lines of code
- It handles JSON and XML parsing out of the box without requiring additional libraries
- It integrates with every major Java testing framework โ TestNG, JUnit 4, JUnit 5
- It supports every authentication mechanism used in real APIs โ Basic Auth, OAuth 1.0, OAuth 2.0, Bearer tokens, API keys, Digest Auth
- It provides built-in support for request/response logging, which is critical for debugging in CI/CD environments
- Its Hamcrest matcher integration makes assertions expressive and readable
Maven Dependency โ Always Have This Ready
Every REST Assured interview may begin with “How do you add REST Assured to your project?” โ have this memorized:
<!-- REST Assured Core -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
<!-- JSON Path for JSON parsing -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>5.4.0</version>
</dependency>
<!-- XML Path for XML parsing -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>xml-path</artifactId>
<version>5.4.0</version>
</dependency>
<!-- JSON Schema Validator -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>5.4.0</version>
</dependency>
<!-- TestNG for test execution -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.8.0</version>
<scope>test</scope>
</dependency>
3. REST Assured Interview Questions 1โ20 โ Beginner Level
These are the REST Assured Interview Questions you will face in the first round of any screening interview. Every single one of these must be answered confidently and completely.
Q1. What is REST Assured and why is it used in API testing?
๐ Explanation
REST Assured is a Java-based DSL (Domain Specific Language) library built specifically for testing RESTful web services. It abstracts the complexity of HTTP communication โ request building, response parsing, and assertion writing โ behind a fluent, readable API.
Before REST Assured, Java developers testing APIs had to use low-level HTTP clients like Apache HttpClient or HttpURLConnection, which required 30โ50 lines of boilerplate just to make a simple GET request and read the response. REST Assured reduces that to 3โ5 lines.
REST Assured is used in API testing because it:
- Integrates seamlessly with Java testing frameworks like TestNG and JUnit
- Provides built-in JSON and XML parsing without external dependencies
- Supports all HTTP methods โ GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS
- Validates status codes, headers, response bodies, and response times out of the box
- Follows BDD syntax that improves test readability and team collaboration
๐ป Code Example
import io.restassured.RestAssured;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class BasicGetTest {
public void testGetUser() {
RestAssured.baseURI = "https://reqres.in";
given()
.header("Content-Type", "application/json")
.when()
.get("/api/users/2")
.then()
.statusCode(200)
.body("data.id", equalTo(2))
.body("data.first_name", equalTo("Janet"));
}
}
๐ฏ Interview Takeaway
In an interview, add this: “REST Assured follows the Given-When-Then structure from BDD, which means even non-technical stakeholders can read and understand our API tests. This is a significant advantage in Agile teams.”
Q2. What are the main features of REST Assured?
๐ Explanation
REST Assured’s feature set is what makes it the most productive API testing library in the Java ecosystem. The key features that interviewers expect you to know are:
BDD-Style Syntax: The given(), when(), then() structure makes tests readable and self-documenting. Tests read like natural language, which reduces onboarding time for new team members.
Built-in Assertions: REST Assured integrates with Hamcrest matchers for expressive assertions. You can validate status codes, headers, response body fields, response time, and content type in a single fluent chain.
JSON and XML Support: JsonPath and XmlPath are included out of the box. You can navigate complex nested JSON structures or XML documents using simple path expressions without any additional libraries.
Authentication Support: REST Assured provides native support for Basic Auth, Digest Auth, OAuth 1.0, OAuth 2.0, Bearer tokens, form-based authentication, and preemptive authentication.
Request and Response Logging: The log() API provides granular logging control โ log everything, log only on failure, log only specific parts like headers or body. This is invaluable for debugging failures in CI/CD pipelines.
Schema Validation: REST Assured can validate that a JSON response conforms to a specific JSON Schema, which is critical for contract testing between microservices.
RequestSpecification and ResponseSpecification: These allow you to define reusable request and response configurations, eliminating code duplication across large test suites.
๐ป Code Example
given()
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.queryParam("page", 1)
.log().all()
.when()
.get("https://reqres.in/api/users")
.then()
.log().ifError()
.statusCode(200)
.contentType(ContentType.JSON)
.body("page", equalTo(1))
.body("data.size()", greaterThan(0))
.time(lessThan(3000L));
๐ฏ Interview Takeaway
“The combination of BDD syntax, built-in logging, and schema validation makes REST Assured suitable for enterprise-scale API testing โ not just simple smoke tests.”
Q3. How do you send a GET request using REST Assured?
๐ Explanation
The GET request is the most fundamental HTTP operation and typically the first thing demonstrated in any REST Assured interview. In REST Assured, GET requests are executed using the get() method inside the when() block.
A GET request retrieves data from a specified resource without modifying anything on the server. It is idempotent โ calling it multiple times produces the same result. GET requests can include query parameters for filtering, sorting, or pagination, but never include a request body.
๐ป Code Example
// Simple GET request
given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.statusCode(200);
// GET request with baseURI and query parameters
RestAssured.baseURI = "https://reqres.in";
given()
.queryParam("page", 2)
.queryParam("per_page", 6)
.when()
.get("/api/users")
.then()
.statusCode(200)
.body("page", equalTo(2))
.body("per_page", equalTo(6));
// GET request with path parameter
given()
.pathParam("userId", 3)
.when()
.get("/api/users/{userId}")
.then()
.statusCode(200)
.body("data.id", equalTo(3));
๐ฏ Interview Takeaway
“Always set baseURI globally using RestAssured.baseURI rather than hardcoding the full URL in every test. This makes switching between environments โ dev, staging, production โ a single line change.”
Q4. How do you validate the response status code in REST Assured?
๐ Explanation
Status code validation is the most basic and mandatory assertion in every API test. It confirms that the API processed your request in the expected way. REST Assured provides the statusCode() method in the then() block for this purpose.
HTTP status codes follow a predictable pattern:
- 2xx โ Success (200 OK, 201 Created, 204 No Content)
- 3xx โ Redirection (301 Moved Permanently, 302 Found)
- 4xx โ Client Error (400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 422 Unprocessable Entity)
- 5xx โ Server Error (500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailable)
Every test should validate the status code first before checking response body content โ a 500 response might still return a JSON body, and without status code validation, your test might incorrectly pass.
๐ป Code Example
// Validate 200 OK
given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.statusCode(200);
// Validate 201 Created for POST
given()
.contentType("application/json")
.body("{ \"name\": \"Ajit\", \"job\": \"QA Lead\" }")
.when()
.post("https://reqres.in/api/users")
.then()
.statusCode(201);
// Validate 404 Not Found
given()
.when()
.get("https://reqres.in/api/users/999")
.then()
.statusCode(404);
// Validate 204 No Content for DELETE
given()
.when()
.delete("https://reqres.in/api/users/2")
.then()
.statusCode(204);
// Using Hamcrest matcher for flexible status code validation
given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.statusCode(anyOf(is(200), is(201)));
๐ฏ Interview Takeaway
“I always validate status code as the first assertion in every test. If the status code is wrong, any body validation that follows is meaningless โ the server might have returned an error response body instead of the expected data.”
Q5. What is the difference between given(), when(), and then() in REST Assured?
๐ Explanation
This is one of the most frequently asked beginner-level REST Assured Interview Questions because it tests both your knowledge of the library and your understanding of BDD principles.
REST Assured follows the Behavior Driven Development (BDD) structure with three distinct phases:
given() โ The setup phase. Everything you need to configure before making the API call goes here. This includes:
- Request headers
- Query parameters and path parameters
- Request body / payload
- Authentication credentials
- Content type
- Base URI and base path
- Request logging
- SSL configuration
when() โ The action phase. This is where you specify what HTTP action to take:
get(url)โ HTTP GETpost(url)โ HTTP POSTput(url)โ HTTP PUTdelete(url)โ HTTP DELETEpatch(url)โ HTTP PATCHhead(url)โ HTTP HEADoptions(url)โ HTTP OPTIONS
then() โ The validation phase. Everything related to asserting the response goes here:
- Status code validation
- Response body validation
- Header validation
- Content type validation
- Response time validation
- Response logging
- Value extraction
๐ป Code Example
given() // SETUP
.baseUri("https://reqres.in")
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.queryParam("page", 1)
.log().all() // Log everything before request
.when() // ACTION
.get("/api/users")
.then() // VALIDATION
.log().ifError() // Log only on failure
.statusCode(200)
.contentType(ContentType.JSON)
.body("page", equalTo(1))
.body("total", greaterThan(0))
.body("data[0].id", notNullValue())
.time(lessThan(5000L));
๐ฏ Interview Takeaway
“The given-when-then structure is not just syntactic sugar โ it enforces separation of concerns in test design. Setup, action, and validation are clearly separated, which makes tests easier to read, maintain, and debug when they fail.”
Q6. How do you add query parameters in REST Assured?
๐ Explanation
Query parameters are key-value pairs appended to the URL after a ? symbol, used to filter, sort, paginate, or customize API responses. In REST Assured, query parameters are added using queryParam() in the given() block.
Multiple query parameters are separated by & in the URL (e.g., /users?page=2&per_page=6). REST Assured automatically handles URL encoding of special characters in parameter values.
๐ป Code Example
// Single query parameter
given()
.queryParam("page", 2)
.when()
.get("https://reqres.in/api/users")
.then()
.statusCode(200)
.body("page", equalTo(2));
// Multiple query parameters
given()
.queryParam("page", 1)
.queryParam("per_page", 3)
.when()
.get("https://reqres.in/api/users")
.then()
.statusCode(200)
.body("data.size()", equalTo(3));
// Using Map for query parameters
Map<String, Object> params = new HashMap<>();
params.put("page", 2);
params.put("per_page", 6);
given()
.queryParams(params)
.when()
.get("https://reqres.in/api/users")
.then()
.statusCode(200);
// Query parameter with special characters (auto URL-encoded)
given()
.queryParam("search", "QA Engineer")
.queryParam("location", "Pune, India")
.when()
.get("https://api.example.com/jobs")
.then()
.statusCode(200);
๐ฏ Interview Takeaway
“I prefer using queryParams(Map) over chaining multiple queryParam() calls when there are more than three parameters. It makes the code cleaner and allows building the parameter map dynamically from test data.”
Q7. How do you send path parameters in REST Assured?
๐ Explanation
Path parameters are dynamic values embedded directly within the URL path, used to identify a specific resource. Unlike query parameters which appear after ?, path parameters are part of the URL structure itself (e.g., /users/2 where 2 is a path parameter).
In REST Assured, path parameters are defined using pathParam() in the given() block and referenced in the URL using curly brace placeholders like {id}.
๐ป Code Example
// Single path parameter
given()
.pathParam("userId", 2)
.when()
.get("https://reqres.in/api/users/{userId}")
.then()
.statusCode(200)
.body("data.id", equalTo(2));
// Multiple path parameters
given()
.pathParam("resourceType", "users")
.pathParam("resourceId", 3)
.when()
.get("https://reqres.in/api/{resourceType}/{resourceId}")
.then()
.statusCode(200);
// Using Map for path parameters
Map<String, Object> pathParams = new HashMap<>();
pathParams.put("version", "v1");
pathParams.put("userId", 5);
given()
.pathParams(pathParams)
.when()
.get("https://api.example.com/{version}/users/{userId}")
.then()
.statusCode(200);
๐ฏ Interview Takeaway
“The key difference between path parameters and query parameters in interviews: path parameters identify WHICH resource you want, query parameters specify HOW you want it returned. /users/2 says ‘give me user 2’. /users?role=admin says ‘give me users filtered by admin role’.”
Q8. How do you validate the response body in REST Assured?
๐ Explanation
Response body validation is where REST Assured truly shines. Using JsonPath expressions and Hamcrest matchers, you can validate any field in any JSON structure โ simple strings, integers, booleans, arrays, nested objects, and collections.
REST Assured uses Groovy’s GPath syntax for JSON navigation, which is similar to XPath but designed for JSON. You can navigate nested structures using dot notation and access array elements using index notation.
๐ป Code Example
// Validate simple field values
given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.statusCode(200)
.body("data.id", equalTo(2))
.body("data.first_name", equalTo("Janet"))
.body("data.last_name", equalTo("Weaver"))
.body("data.email", containsString("@reqres.in"));
// Validate array size and content
given()
.when()
.get("https://reqres.in/api/users?page=1")
.then()
.statusCode(200)
.body("data.size()", equalTo(6))
.body("data.id", hasItems(1, 2, 3))
.body("data.first_name", hasItem("George"));
// Validate nested objects
given()
.when()
.get("https://jsonplaceholder.typicode.com/users/1")
.then()
.statusCode(200)
.body("address.city", equalTo("Gwenborough"))
.body("address.geo.lat", equalTo("-37.3159"))
.body("company.name", notNullValue());
// Validate using not() matcher
given()
.when()
.get("https://reqres.in/api/users?page=1")
.then()
.body("data", not(empty()))
.body("data[0].email", not(emptyOrNullString()));
๐ฏ Interview Takeaway
“For complex response bodies, I always validate the most business-critical fields rather than every single field. Validating everything creates brittle tests that break on minor API changes. Focus on fields that indicate correctness of business logic.”
Q9. How do you parse JSON response in REST Assured?
๐ Explanation
JSON parsing in REST Assured allows you to extract specific values from the response for validation, reuse in subsequent requests, or storing in variables for comparison. REST Assured provides jsonPath() method which returns a JsonPath object that you can use to navigate and extract data from any JSON structure.
๐ป Code Example
// Extract a single string value
Response response = given()
.when()
.get("https://reqres.in/api/users/2");
String email = response.jsonPath().getString("data.email");
String firstName = response.jsonPath().getString("data.first_name");
int id = response.jsonPath().getInt("data.id");
System.out.println("Email: " + email);
System.out.println("First Name: " + firstName);
System.out.println("ID: " + id);
// Extract list of values
Response listResponse = given()
.when()
.get("https://reqres.in/api/users?page=1");
List<String> emails = listResponse.jsonPath().getList("data.email");
List<Integer> ids = listResponse.jsonPath().getList("data.id");
System.out.println("All emails: " + emails);
// Extract using .then().extract().path()
String email2 = given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.extract()
.path("data.email");
// Extract entire response as a Map
Map<String, Object> dataMap = given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.extract()
.path("data");
System.out.println("User data map: " + dataMap);
๐ฏ Interview Takeaway
“I use jsonPath() when I need to extract multiple values from a response. I use extract().path() when I only need one specific value. For chaining API calls โ where a value from one response becomes the input for the next โ extract and store is essential.”
Q10. What is the Response object in REST Assured?
๐ Explanation
The Response object in REST Assured represents the complete HTTP response returned by the server. It contains everything โ the status code, all response headers, the response body in its raw form, cookies, and response time. Capturing the response as a Response object gives you maximum flexibility for validation and data extraction.
๐ป Code Example
// Capture complete response
Response response = given()
.when()
.get("https://reqres.in/api/users/2");
// Access different parts of the response
int statusCode = response.getStatusCode();
String body = response.getBody().asString();
String contentType = response.getContentType();
long responseTime = response.getTime();
String headerValue = response.getHeader("Content-Type");
System.out.println("Status: " + statusCode);
System.out.println("Content-Type: " + contentType);
System.out.println("Response Time: " + responseTime + "ms");
System.out.println("Body: " + body);
// Extract JSON fields from Response object
String firstName = response.jsonPath().getString("data.first_name");
int userId = response.jsonPath().getInt("data.id");
// Check if field exists
boolean hasSupport = response.jsonPath().get("support") != null;
// Get all cookies
Map<String, String> cookies = response.getCookies();
// Get response headers as a map
Headers headers = response.getHeaders();
for (Header header : headers) {
System.out.println(header.getName() + ": " + header.getValue());
}
๐ฏ Interview Takeaway
“The Response object is essential in scenarios where you need to use the same response for multiple validations or extract multiple values. Capturing it once avoids making the same API call multiple times.”
Q11. How do you handle headers in REST Assured?
๐ Explanation
HTTP headers carry metadata about the request or response โ authentication tokens, content type, accepted formats, caching instructions, and custom application headers. In REST Assured, request headers are added in the given() block and response headers are validated in the then() block.
๐ป Code Example
// Add single header
given()
.header("Content-Type", "application/json")
.when()
.get("https://reqres.in/api/users");
// Add multiple headers
given()
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.header("Authorization", "Bearer eyJhbGciOiJIUzI1NiJ9...")
.header("X-Request-ID", "req-12345")
.header("X-API-Version", "2.0")
.when()
.get("https://api.example.com/users");
// Use Headers object for multiple headers
Headers headers = new Headers(
new Header("Content-Type", "application/json"),
new Header("Accept", "application/json"),
new Header("Authorization", "Bearer token123")
);
given()
.headers(headers)
.when()
.get("https://api.example.com/users");
// Use Map for headers
Map<String, String> headersMap = new HashMap<>();
headersMap.put("Content-Type", "application/json");
headersMap.put("Authorization", "Bearer token123");
given()
.headers(headersMap)
.when()
.get("https://api.example.com/users");
// Validate response headers
given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.statusCode(200)
.header("Content-Type", containsString("application/json"))
.header("Transfer-Encoding", equalTo("chunked"));
๐ฏ Interview Takeaway
“In production frameworks, authorization headers are never hardcoded in individual tests. They are set once in a RequestSpecification base configuration and shared across all tests that require authentication.”
Q12. How do you perform a POST request with a JSON body in REST Assured?
๐ Explanation
POST requests create new resources on the server and require a request body containing the data to be created. In REST Assured, the JSON payload is passed using the body() method in the given() block, and the Content-Type header must be set to application/json.
๐ป Code Example
// POST with hardcoded JSON string
given()
.contentType("application/json")
.body("{ \"name\": \"Ajit Marathe\", \"job\": \"QA Automation Lead\" }")
.when()
.post("https://reqres.in/api/users")
.then()
.statusCode(201)
.body("name", equalTo("Ajit Marathe"))
.body("job", equalTo("QA Automation Lead"))
.body("id", notNullValue())
.body("createdAt", notNullValue());
// POST using a POJO (most professional approach)
public class UserRequest {
private String name;
private String job;
// Constructor, getters, setters
public UserRequest(String name, String job) {
this.name = name;
this.job = job;
}
public String getName() { return name; }
public String getJob() { return job; }
}
UserRequest newUser = new UserRequest("Priya Sharma", "SDET");
given()
.contentType(ContentType.JSON)
.body(newUser)
.when()
.post("https://reqres.in/api/users")
.then()
.statusCode(201)
.body("name", equalTo("Priya Sharma"));
// POST with JSON from external file
String jsonBody = new String(Files.readAllBytes(
Paths.get("src/test/resources/payloads/createUser.json")));
given()
.contentType(ContentType.JSON)
.body(jsonBody)
.when()
.post("https://reqres.in/api/users")
.then()
.statusCode(201);
๐ฏ Interview Takeaway
“I always use POJO classes for request bodies in production frameworks. Hardcoded JSON strings are error-prone โ a missing quote or bracket breaks the test and the error message is confusing. With POJOs, Jackson handles serialization automatically and you get compile-time safety.”
Q13. What is Content-Type and how do you set it in REST Assured?
๐ Explanation
Content-Type is an HTTP header that tells the server what format the request body is in. Without it, the server cannot parse the request body correctly and will likely return a 400 Bad Request or 415 Unsupported Media Type error. It is mandatory for POST, PUT, and PATCH requests.
Common Content-Type values in API testing:
application/jsonโ JSON format (most common in modern APIs)application/xmlโ XML formatapplication/x-www-form-urlencodedโ HTML form datamultipart/form-dataโ File uploadstext/plainโ Plain text
๐ป Code Example
// Set as string
given()
.contentType("application/json")
.body("{ \"name\": \"test\" }")
.when()
.post("https://reqres.in/api/users");
// Set using ContentType enum (preferred โ type safe)
given()
.contentType(ContentType.JSON)
.body(userPojo)
.when()
.post("https://reqres.in/api/users");
// XML content type
given()
.contentType(ContentType.XML)
.body("<user><name>Ajit</name></user>")
.when()
.post("https://api.example.com/users");
// Form URL encoded
given()
.contentType("application/x-www-form-urlencoded")
.formParam("username", "ajit@qatribe.in")
.formParam("password", "securepass")
.when()
.post("https://api.example.com/login");
// Validate content type in response
given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.contentType(ContentType.JSON);
๐ฏ Interview Takeaway
“Use ContentType.JSON enum instead of the string \"application/json\" wherever possible. It prevents typos and is IDE-searchable. The enum values in REST Assured also automatically handle charset negotiation.”
Q14. How do you log requests and responses in REST Assured?
๐ Explanation
Logging is one of the most practically important features of REST Assured for real-world testing. When tests fail in CI/CD pipelines, logs are often the only information you have to diagnose the failure. REST Assured provides granular logging control at both the request and response level.
๐ป Code Example
// Log everything (request + response)
given()
.log().all()
.when()
.get("https://reqres.in/api/users/2")
.then()
.log().all()
.statusCode(200);
// Log only on failure (most efficient for CI/CD)
given()
.log().ifValidationFails()
.when()
.get("https://reqres.in/api/users/2")
.then()
.log().ifError()
.statusCode(200);
// Log specific parts
given()
.log().headers()
.log().body()
.log().params()
.when()
.get("https://reqres.in/api/users/2")
.then()
.log().status()
.log().headers()
.log().body();
// Enable global logging for all tests
RestAssured.filters(new RequestLoggingFilter(), new ResponseLoggingFilter());
// Log to a file instead of console
PrintStream fileOut = new PrintStream(new File("test-logs/api-test.log"));
given()
.filter(new RequestLoggingFilter(fileOut))
.filter(new ResponseLoggingFilter(fileOut))
.when()
.get("https://reqres.in/api/users");
๐ฏ Interview Takeaway
“In CI/CD environments, I use log().ifValidationFails() for requests and log().ifError() for responses. This avoids flooding build logs with thousands of lines from passing tests while still capturing full details for failures.”
Q15. How do you validate response time in REST Assured?
๐ Explanation
Response time validation is performance testing at the API level. It ensures your APIs meet SLA (Service Level Agreement) requirements. REST Assured provides the time() method in the then() block which works with Hamcrest matchers to assert response time against a threshold.
๐ป Code Example
// Validate response time is less than 2 seconds
given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.statusCode(200)
.time(lessThan(2000L));
// Validate response time is within a range
given()
.when()
.get("https://reqres.in/api/users")
.then()
.time(both(greaterThan(0L)).and(lessThan(3000L)));
// Extract response time for reporting
Response response = given()
.when()
.get("https://reqres.in/api/users/2");
long responseTime = response.getTime();
System.out.println("Response time: " + responseTime + "ms");
// Using TimeUnit for better readability
given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.time(lessThan(2L), TimeUnit.SECONDS);
๐ฏ Interview Takeaway
“Response time validation in REST Assured is functional performance testing, not load testing. It validates individual API calls under normal conditions. For actual load and stress testing, you need tools like JMeter or Gatling.”
Q16. What is Hamcrest and how does it work with REST Assured?
๐ Explanation
Hamcrest is a library of matcher objects that allow you to write expressive, human-readable assertions. The name “Hamcrest” is an anagram of “matchers.” It is not REST Assured-specific โ it is used with JUnit, TestNG, and many other Java testing frameworks โ but REST Assured integrates it deeply for response validation.
The key Hamcrest matchers you must know for REST Assured interviews:
| Matcher | Usage |
|---|---|
equalTo(x) | Exact match |
not(x) | Negation |
containsString(s) | String contains |
startsWith(s) | String starts with |
endsWith(s) | String ends with |
greaterThan(n) | Numeric comparison |
lessThan(n) | Numeric comparison |
hasItem(x) | Collection contains item |
hasItems(x, y) | Collection contains all items |
hasSize(n) | Collection size |
notNullValue() | Not null |
nullValue() | Is null |
empty() | Empty collection |
emptyOrNullString() | Empty or null string |
anyOf(m1, m2) | OR condition |
allOf(m1, m2) | AND condition |
instanceOf(Class) | Type check |
๐ป Code Example
import static org.hamcrest.Matchers.*;
given()
.when()
.get("https://reqres.in/api/users?page=1")
.then()
.statusCode(200)
.body("page", equalTo(1))
.body("total", greaterThan(0))
.body("data", not(empty()))
.body("data.size()", lessThan(10))
.body("data[0].email", containsString("@reqres.in"))
.body("data[0].first_name", notNullValue())
.body("data.id", hasItems(1, 2, 3))
.body("data.email", everyItem(containsString("@")))
.body("support.url", startsWith("https://"))
.body("support.text", not(emptyOrNullString()));
๐ฏ Interview Takeaway
“Hamcrest’s everyItem() matcher is extremely useful for validating collections โ for example, verifying that every email in a list of users contains ‘@’, or that every price in a product list is greater than zero. This is much cleaner than writing a loop.”
Q17. How do you extract values from a response in REST Assured?
๐ Explanation
Value extraction from responses is essential for dynamic testing scenarios โ using a created resource’s ID in a subsequent request, comparing values between API calls, or building data-driven tests. REST Assured provides multiple extraction mechanisms depending on your use case.
๐ป Code Example
// Method 1: Using Response object
Response response = given()
.when()
.get("https://reqres.in/api/users/2");
String email = response.jsonPath().getString("data.email");
int id = response.jsonPath().getInt("data.id");
// Method 2: Using extract().path()
String firstName = given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.extract()
.path("data.first_name");
// Method 3: Extract entire Response for multiple uses
Response fullResponse = given()
.when()
.get("https://reqres.in/api/users?page=1")
.then()
.extract()
.response();
List<String> emails = fullResponse.jsonPath().getList("data.email");
int total = fullResponse.jsonPath().getInt("total");
// Method 4: Extract and use in next request (chaining APIs)
// Step 1: Create a user and get the ID
String userId = given()
.contentType(ContentType.JSON)
.body("{ \"name\": \"Chain Test\", \"job\": \"tester\" }")
.when()
.post("https://reqres.in/api/users")
.then()
.statusCode(201)
.extract()
.path("id");
System.out.println("Created user ID: " + userId);
// Step 2: Use extracted ID in next request
given()
.pathParam("id", userId)
.when()
.get("https://reqres.in/api/users/{id}")
.then()
.statusCode(200); // or 404 since reqres is a mock
// Method 5: Extract as POJO
UserResponse user = given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.extract()
.as(UserResponse.class);
๐ฏ Interview Takeaway
“API chaining โ where you create a resource in one request and use its ID or token in subsequent requests โ is a core pattern in real automation frameworks. REST Assured’s extract mechanism makes this clean and maintainable.”
Q18. How do you reuse request specification in REST Assured?
๐ Explanation
RequestSpecification is one of the most important framework-level concepts in REST Assured. It allows you to define common request configurations โ base URI, headers, authentication, content type โ once and reuse them across all tests. This eliminates code duplication and makes changing global settings (like switching environments or updating auth tokens) a single-line change.
๐ป Code Example
// Define reusable RequestSpecification
RequestSpecification requestSpec = new RequestSpecBuilder()
.setBaseUri("https://reqres.in")
.setBasePath("/api")
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.addHeader("X-API-Version", "1.0")
.setRelaxedHTTPSValidation()
.log(LogDetail.ALL)
.build();
// Use in multiple tests
given()
.spec(requestSpec)
.when()
.get("/users/2")
.then()
.statusCode(200);
given()
.spec(requestSpec)
.body("{ \"name\": \"test\" }")
.when()
.post("/users")
.then()
.statusCode(201);
// Set globally for all tests
RestAssured.requestSpecification = requestSpec;
// Combine with additional spec in specific test
RequestSpecification adminSpec = new RequestSpecBuilder()
.addRequestSpecification(requestSpec)
.addHeader("X-Admin-Token", "admin-secret-token")
.build();
๐ฏ Interview Takeaway
“In enterprise frameworks, I define the base RequestSpecification in a @BeforeSuite or @BeforeClass method and assign it to RestAssured.requestSpecification. Every test automatically inherits it without any boilerplate. Individual tests can add extra headers or parameters on top of the base spec.”
Q19. What is baseURI in REST Assured and how do you configure it?
๐ Explanation
RestAssured.baseURI is the root URL that all your API tests run against. Instead of hardcoding https://api.yourapp.com in every single test, you set it once and use relative paths like /users or /products/1 in your tests. This makes environment switching trivial โ change one line to switch from staging to production.
๐ป Code Example
// Set globally for all tests
RestAssured.baseURI = "https://reqres.in";
RestAssured.basePath = "/api";
RestAssured.port = 443;
// Now all tests use relative paths
given()
.when()
.get("/users/2") // Becomes https://reqres.in/api/users/2
.then()
.statusCode(200);
// Using environment-based configuration
public class TestConfig {
public static void setup() {
String environment = System.getProperty("env", "staging");
switch (environment) {
case "dev":
RestAssured.baseURI = "https://dev-api.qatribe.in";
break;
case "staging":
RestAssured.baseURI = "https://staging-api.qatribe.in";
break;
case "production":
RestAssured.baseURI = "https://api.qatribe.in";
break;
default:
RestAssured.baseURI = "https://staging-api.qatribe.in";
}
}
}
// Using config.properties file
Properties props = new Properties();
props.load(new FileInputStream("src/test/resources/config.properties"));
RestAssured.baseURI = props.getProperty("base.uri");
๐ฏ Interview Takeaway
“Never hardcode base URIs in tests. Always drive them from a config file or system property. This enables running the same test suite against different environments using -Denv=staging in the Maven command โ essential for CI/CD pipelines.”
Q20. How do you handle all HTTP methods in REST Assured?
๐ Explanation
REST Assured provides direct methods for all standard HTTP verbs, making CRUD operation testing straightforward. Understanding which method maps to which operation is fundamental โ both for REST Assured and for general API knowledge.
๐ป Code Example
RestAssured.baseURI = "https://reqres.in";
// GET โ Retrieve resource
given()
.when()
.get("/api/users/2")
.then()
.statusCode(200);
// POST โ Create resource
given()
.contentType(ContentType.JSON)
.body("{ \"name\": \"Ajit\", \"job\": \"QA Lead\" }")
.when()
.post("/api/users")
.then()
.statusCode(201)
.body("name", equalTo("Ajit"));
// PUT โ Full update (replace entire resource)
given()
.contentType(ContentType.JSON)
.body("{ \"name\": \"Ajit Updated\", \"job\": \"Senior QA Lead\" }")
.when()
.put("/api/users/2")
.then()
.statusCode(200)
.body("name", equalTo("Ajit Updated"))
.body("updatedAt", notNullValue());
// PATCH โ Partial update (modify specific fields only)
given()
.contentType(ContentType.JSON)
.body("{ \"job\": \"Automation Architect\" }")
.when()
.patch("/api/users/2")
.then()
.statusCode(200)
.body("job", equalTo("Automation Architect"));
// DELETE โ Remove resource
given()
.when()
.delete("/api/users/2")
.then()
.statusCode(204);
// HEAD โ Retrieve headers only (no response body)
given()
.when()
.head("/api/users/2")
.then()
.statusCode(200)
.header("Content-Type", notNullValue());
๐ฏ Interview Takeaway
“The distinction between PUT and PATCH is a common interview trap. PUT replaces the entire resource โ if you omit a field, it gets deleted. PATCH only updates the fields you specify โ everything else stays unchanged. Always clarify this distinction when asked.”
4. REST Assured Interview Questions 21โ40 โ Intermediate Level
These REST Assured Interview Questions separate candidates who have read about the tool from those who have actually used it in real projects.
Q21. How do you handle authentication in REST Assured?
๐ Explanation
Almost every production API requires authentication. REST Assured provides built-in support for all common authentication mechanisms, making it straightforward to test secured endpoints without manual token management.
๐ป Code Example
// Basic Authentication
given()
.auth().basic("username", "password")
.when()
.get("https://api.example.com/protected")
.then()
.statusCode(200);
// Preemptive Basic Auth (sends credentials without waiting for 401 challenge)
given()
.auth().preemptive().basic("username", "password")
.when()
.get("https://api.example.com/protected")
.then()
.statusCode(200);
// Bearer Token / API Key in header
String token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyMSJ9...";
given()
.header("Authorization", "Bearer " + token)
.when()
.get("https://api.example.com/protected")
.then()
.statusCode(200);
// OAuth2 Bearer Token
given()
.auth().oauth2(token)
.when()
.get("https://api.example.com/protected")
.then()
.statusCode(200);
// Login and extract token for reuse
String authToken = given()
.contentType(ContentType.JSON)
.body("{ \"email\": \"eve.holt@reqres.in\", \"password\": \"cityslicka\" }")
.when()
.post("https://reqres.in/api/login")
.then()
.statusCode(200)
.extract()
.path("token");
// Use extracted token in subsequent requests
given()
.header("Authorization", "Bearer " + authToken)
.when()
.get("https://reqres.in/api/users")
.then()
.statusCode(200);
Q22. How do you perform JSON Schema Validation in REST Assured?
๐ Explanation
JSON Schema Validation verifies that the structure of a JSON response conforms to a predefined schema โ correct field names, correct data types, required fields present, values within allowed ranges. This is critical for contract testing between microservices.
๐ป Code Example
// Add dependency: io.rest-assured:json-schema-validator
// Create schema file: src/test/resources/schemas/user-schema.json
/*
{
"$schema": "http://json-schema.org/draft-07/schema",
"type": "object",
"required": ["data", "support"],
"properties": {
"data": {
"type": "object",
"required": ["id", "email", "first_name", "last_name"],
"properties": {
"id": { "type": "integer" },
"email": { "type": "string", "format": "email" },
"first_name": { "type": "string" },
"last_name": { "type": "string" },
"avatar": { "type": "string", "format": "uri" }
}
}
}
}
*/
import static io.restassured.module.jsv.JsonSchemaValidator.*;
given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.statusCode(200)
.body(matchesJsonSchemaInClasspath("schemas/user-schema.json"));
๐ฏ Interview Takeaway
“JSON Schema Validation is my go-to approach for contract testing. When a backend developer changes the API response structure without telling QA, schema validation catches it immediately โ even if the functional test still passes because the data itself is valid.”
Q23. How do you handle cookies in REST Assured?
๐ Explanation
Cookies are used for session management, authentication, and state maintenance in web APIs. REST Assured provides complete cookie handling โ adding cookies to requests, extracting cookies from responses, and validating cookie attributes.
๐ป Code Example
// Add cookie to request
given()
.cookie("sessionId", "abc123xyz")
.when()
.get("https://api.example.com/dashboard")
.then()
.statusCode(200);
// Add multiple cookies using Cookies object
Cookies cookies = new Cookies(
new Cookie.Builder("sessionId", "abc123").build(),
new Cookie.Builder("userId", "42").build()
);
given()
.cookies(cookies)
.when()
.get("https://api.example.com/profile");
// Extract cookies from response
Response response = given()
.contentType(ContentType.JSON)
.body("{ \"username\": \"ajit\", \"password\": \"pass\" }")
.when()
.post("https://api.example.com/login");
String sessionCookie = response.getCookie("sessionId");
Map<String, String> allCookies = response.getCookies();
// Validate cookie in response
given()
.when()
.get("https://api.example.com/set-cookie")
.then()
.cookie("cookieName", "expectedValue");
Q24. How do you test file upload APIs in REST Assured?
๐ Explanation
File upload testing is a common real-world scenario โ profile pictures, documents, CSV imports. REST Assured supports multipart file uploads using the multiPart() method.
๐ป Code Example
// Upload a single file
File uploadFile = new File("src/test/resources/testfiles/profile.jpg");
given()
.multiPart("file", uploadFile)
.header("Authorization", "Bearer " + token)
.when()
.post("https://api.example.com/upload/profile-picture")
.then()
.statusCode(200)
.body("fileName", equalTo("profile.jpg"))
.body("url", notNullValue());
// Upload with additional form fields
given()
.multiPart("file", new File("src/test/resources/testfiles/report.pdf"))
.multiPart("description", "Monthly QA Report")
.multiPart("category", "reports")
.header("Authorization", "Bearer " + token)
.when()
.post("https://api.example.com/documents/upload")
.then()
.statusCode(201);
// Upload multiple files
given()
.multiPart("files", new File("src/test/resources/file1.jpg"))
.multiPart("files", new File("src/test/resources/file2.jpg"))
.when()
.post("https://api.example.com/upload/bulk")
.then()
.statusCode(200)
.body("uploadedCount", equalTo(2));
Q25. How do you handle SSL/HTTPS in REST Assured?
๐ Explanation
By default, REST Assured validates SSL certificates. In testing environments, self-signed certificates are common, and strict SSL validation would cause every test to fail. REST Assured provides relaxedHTTPSValidation() to disable strict certificate checking.
๐ป Code Example
// Disable SSL validation for self-signed certs (test environments only)
given()
.relaxedHTTPSValidation()
.when()
.get("https://self-signed.example.com/api/users")
.then()
.statusCode(200);
// Set globally for all tests
RestAssured.useRelaxedHTTPSValidation();
// In RequestSpecBuilder
RequestSpecification spec = new RequestSpecBuilder()
.setBaseUri("https://staging-api.qatribe.in")
.setRelaxedHTTPSValidation()
.build();
๐ฏ Interview Takeaway
“Always use relaxedHTTPSValidation() in dev and staging environments with self-signed certificates, but never in production tests. Production environments should have valid SSL certificates and your tests should validate them properly.”
Q26. How do you implement data-driven testing with REST Assured?
๐ Explanation
Data-driven testing runs the same test with multiple sets of input data. In REST Assured with TestNG, this is implemented using @DataProvider โ a powerful pattern for testing APIs with various valid inputs, edge cases, and invalid inputs.
๐ป Code Example
public class DataDrivenAPITest {
@DataProvider(name = "userData")
public Object[][] getUserData() {
return new Object[][] {
{ "eve.holt@reqres.in", "cityslicka", 200, "QpwL5tpe" },
{ "invalid@email.com", "wrongpassword", 400, null },
{ "", "password", 400, null }
};
}
@Test(dataProvider = "userData")
public void testLogin(String email, String password,
int expectedStatus, String expectedToken) {
String body = String.format(
"{ \"email\": \"%s\", \"password\": \"%s\" }",
email, password);
ValidatableResponse response = given()
.contentType(ContentType.JSON)
.body(body)
.when()
.post("https://reqres.in/api/login")
.then()
.statusCode(expectedStatus);
if (expectedToken != null) {
response.body("token", equalTo(expectedToken));
}
}
// Data driven from external Excel/CSV
@DataProvider(name = "excelData")
public Object[][] getExcelData() throws Exception {
// Read from Excel using Apache POI
List<Map<String, String>> testData = ExcelReader.read(
"src/test/resources/testdata/api-test-data.xlsx", "LoginTests");
Object[][] data = new Object[testData.size()][1];
for (int i = 0; i < testData.size(); i++) {
data[i][0] = testData.get(i);
}
return data;
}
}
Q27. What is ResponseSpecification and how do you use it?
๐ Explanation
ResponseSpecification is the response-side counterpart of RequestSpecification. It allows you to define common response validations โ expected status code, content type, response time โ once and reuse them across multiple tests.
๐ป Code Example
// Define reusable ResponseSpecification
ResponseSpecification successSpec = new ResponseSpecBuilder()
.expectStatusCode(200)
.expectContentType(ContentType.JSON)
.expectResponseTime(lessThan(3000L))
.expectBody("data", notNullValue())
.build();
ResponseSpecification createdSpec = new ResponseSpecBuilder()
.expectStatusCode(201)
.expectContentType(ContentType.JSON)
.expectBody("id", notNullValue())
.expectBody("createdAt", notNullValue())
.build();
// Use in tests
given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.spec(successSpec)
.body("data.first_name", equalTo("Janet"));
given()
.contentType(ContentType.JSON)
.body("{ \"name\": \"Ajit\", \"job\": \"QA Lead\" }")
.when()
.post("https://reqres.in/api/users")
.then()
.spec(createdSpec)
.body("name", equalTo("Ajit"));
// Set globally
RestAssured.responseSpecification = successSpec;
Q28. How do you handle XML responses in REST Assured?
๐ Explanation
While JSON is dominant in modern APIs, many enterprise systems still use XML โ SOAP services, payment gateways, government APIs. REST Assured supports XML parsing through XmlPath, which uses GPath syntax similar to XPath.
๐ป Code Example
// Validate XML response
given()
.when()
.get("https://api.example.com/users/2.xml")
.then()
.statusCode(200)
.contentType(ContentType.XML)
.body("user.id", equalTo("2"))
.body("user.name", equalTo("Ajit Marathe"))
.body("user.email", containsString("@"));
// Extract from XML
String name = given()
.accept(ContentType.XML)
.when()
.get("https://api.example.com/users/1")
.then()
.extract()
.path("user.name");
// Full XML response parsing
Response xmlResponse = given()
.accept(ContentType.XML)
.when()
.get("https://api.example.com/users");
XmlPath xmlPath = xmlResponse.xmlPath();
String firstUserName = xmlPath.getString("users.user[0].name");
List<String> allNames = xmlPath.getList("users.user.name");
Q29. How do you use filters in REST Assured?
๐ Explanation
Filters in REST Assured are request/response interceptors. They run before the request is sent and after the response is received, making them perfect for cross-cutting concerns โ logging, authentication token injection, response caching, and request modification.
๐ป Code Example
// Built-in logging filters
given()
.filter(new RequestLoggingFilter())
.filter(new ResponseLoggingFilter())
.when()
.get("https://reqres.in/api/users");
// Custom filter for adding auth token automatically
public class AuthTokenFilter implements Filter {
private final String token;
public AuthTokenFilter(String token) {
this.token = token;
}
@Override
public Response filter(FilterableRequestSpecification req,
FilterableResponseSpecification res,
FilterContext ctx) {
req.header("Authorization", "Bearer " + token);
return ctx.next(req, res);
}
}
// Use custom filter
given()
.filter(new AuthTokenFilter(authToken))
.when()
.get("https://api.example.com/protected")
.then()
.statusCode(200);
// Add filter globally
RestAssured.filters(new AuthTokenFilter(token),
new RequestLoggingFilter(),
new ResponseLoggingFilter());
Q30. How do you mock API responses in REST Assured tests?
๐ Explanation
WireMock is the most popular tool for mocking API responses in Java. It integrates seamlessly with REST Assured, allowing you to simulate API behavior โ including error responses, timeouts, and network failures โ without depending on the actual backend.
๐ป Code Example
// Add dependency: com.github.tomakehurst:wiremock-jre8
public class MockAPITest {
@Rule
public WireMockRule wireMockRule = new WireMockRule(8080);
@Test
public void testWithMockedResponse() {
// Setup mock
stubFor(get(urlEqualTo("/api/users/1"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{ \"id\": 1, \"name\": \"Mocked User\" }")));
// Test against mock
given()
.baseUri("http://localhost:8080")
.when()
.get("/api/users/1")
.then()
.statusCode(200)
.body("name", equalTo("Mocked User"));
}
@Test
public void testAPITimeoutBehavior() {
stubFor(get(urlEqualTo("/api/slow"))
.willReturn(aResponse()
.withFixedDelay(5000)
.withStatus(200)));
// Verify timeout handling
given()
.baseUri("http://localhost:8080")
.when()
.get("/api/slow")
.then()
.time(greaterThan(4000L));
}
}
Q31. How do you implement a complete API Testing Framework with REST Assured?
๐ Explanation
This is the most important question in senior REST Assured interviews. A production-grade framework is not just test classes โ it is a complete structure with configuration management, base classes, utility helpers, test data management, and reporting integration.
Framework Structure:
src/
โโโ main/java/
โ โโโ framework/
โ โโโ config/
โ โ โโโ ConfigManager.java
โ โ โโโ config.properties
โ โโโ base/
โ โ โโโ BaseTest.java
โ โโโ utils/
โ โ โโโ RequestHelper.java
โ โ โโโ AuthHelper.java
โ โ โโโ JsonHelper.java
โ โโโ endpoints/
โ โโโ APIEndpoints.java
โโโ test/java/
โโโ tests/
โโโ UserTests.java
โโโ AuthTests.java
๐ป Code Example โ ConfigManager.java
public class ConfigManager {
private static Properties props;
static {
try {
props = new Properties();
String env = System.getProperty("env", "staging");
props.load(new FileInputStream(
"src/main/resources/" + env + ".config.properties"));
} catch (Exception e) {
throw new RuntimeException("Failed to load config", e);
}
}
public static String getBaseUri() {
return props.getProperty("base.uri");
}
public static String getAdminToken() {
return props.getProperty("admin.token");
}
}
๐ป Code Example โ BaseTest.java
public class BaseTest {
protected RequestSpecification requestSpec;
protected ResponseSpecification responseSpec;
@BeforeSuite
public void setupSuite() {
// Configure REST Assured globally
RestAssured.baseURI = ConfigManager.getBaseUri();
RestAssured.useRelaxedHTTPSValidation();
}
@BeforeMethod
public void setupMethod() {
requestSpec = new RequestSpecBuilder()
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.addHeader("Authorization", "Bearer " + getAuthToken())
.log(LogDetail.ALL)
.build();
responseSpec = new ResponseSpecBuilder()
.expectContentType(ContentType.JSON)
.expectResponseTime(lessThan(5000L))
.build();
}
private String getAuthToken() {
return given()
.contentType(ContentType.JSON)
.body("{ \"email\": \"" + ConfigManager.getAdminEmail() +
"\", \"password\": \"" + ConfigManager.getAdminPassword() + "\" }")
.when()
.post("/auth/login")
.then()
.statusCode(200)
.extract()
.path("token");
}
}
Q32. How do you handle dynamic tokens in REST Assured framework?
๐ Explanation
In real applications, tokens expire. A production framework must handle token refresh automatically โ obtaining a new token when the current one expires, without failing tests or requiring manual intervention.
๐ป Code Example
public class TokenManager {
private static String token;
private static long tokenExpiryTime;
public static synchronized String getValidToken() {
if (token == null || System.currentTimeMillis() > tokenExpiryTime) {
refreshToken();
}
return token;
}
private static void refreshToken() {
Response response = given()
.contentType(ContentType.JSON)
.body(getLoginPayload())
.when()
.post(ConfigManager.getBaseUri() + "/auth/login");
if (response.statusCode() == 200) {
token = response.jsonPath().getString("access_token");
int expiresIn = response.jsonPath().getInt("expires_in");
tokenExpiryTime = System.currentTimeMillis() + (expiresIn * 1000L) - 30000L;
// Subtract 30 seconds as safety buffer
} else {
throw new RuntimeException("Token refresh failed: " + response.body().asString());
}
}
}
// Usage in tests
given()
.header("Authorization", "Bearer " + TokenManager.getValidToken())
.when()
.get("/api/protected-resource")
.then()
.statusCode(200);
Q33. How do you integrate REST Assured with Allure reporting?
๐ Explanation
Allure is the most popular reporting framework for Java API tests. It generates beautiful, interactive HTML reports with step-by-step details, screenshots, and attachments. Integrating REST Assured with Allure gives stakeholders a clear view of test results.
๐ป Code Example
// Add dependencies: io.qameta.allure:allure-testng, io.qameta.allure:allure-rest-assured
// Add AllureRestAssured filter globally
RestAssured.filters(new AllureRestAssured());
// Use Allure annotations in tests
@Feature("User Management API")
@Story("Get User by ID")
public class UserAPITest extends BaseTest {
@Test
@Severity(SeverityLevel.CRITICAL)
@Description("Verify that getting a user by valid ID returns correct user data")
public void testGetUserById() {
Allure.step("Send GET request for user ID 2", () -> {
given()
.spec(requestSpec)
.when()
.get("/users/2")
.then()
.spec(responseSpec)
.statusCode(200)
.body("data.id", equalTo(2))
.body("data.first_name", equalTo("Janet"));
});
}
}
Q34. How do you run REST Assured tests in parallel?
๐ Explanation
Parallel test execution significantly reduces overall test suite runtime. In TestNG with REST Assured, parallel execution requires careful management of shared state โ each thread must use independent request/response specifications.
๐ป Code Example
<!-- testng.xml configuration for parallel execution -->
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="API Test Suite" parallel="methods" thread-count="5">
<test name="User API Tests">
<classes>
<class name="tests.UserAPITest"/>
<class name="tests.AuthAPITest"/>
</classes>
</test>
</suite>
// Thread-safe BaseTest using ThreadLocal
public class BaseTest {
private static ThreadLocal<RequestSpecification> requestSpec = new ThreadLocal<>();
@BeforeMethod
public void setup() {
RequestSpecification spec = new RequestSpecBuilder()
.setBaseUri(ConfigManager.getBaseUri())
.addHeader("Authorization", "Bearer " + TokenManager.getValidToken())
.addHeader("Content-Type", "application/json")
.build();
requestSpec.set(spec);
}
protected RequestSpecification getSpec() {
return requestSpec.get();
}
@AfterMethod
public void cleanup() {
requestSpec.remove();
}
}
Q35. How do you implement retry logic for flaky API tests?
๐ป Code Example
// TestNG RetryAnalyzer
public class RetryAnalyzer implements IRetryAnalyzer {
private int retryCount = 0;
private static final int MAX_RETRY = 3;
@Override
public boolean retry(ITestResult result) {
if (retryCount < MAX_RETRY) {
retryCount++;
System.out.println("Retrying test: " + result.getName()
+ " (Attempt " + retryCount + " of " + MAX_RETRY + ")");
return true;
}
return false;
}
}
// Apply to tests
@Test(retryAnalyzer = RetryAnalyzer.class)
public void testFlakeyEndpoint() {
given()
.spec(requestSpec)
.when()
.get("/api/sometimes-slow-endpoint")
.then()
.statusCode(200)
.time(lessThan(2000L));
}
6. REST Assured Interview Questions 61โ80 โ Architect Level
Q36. How do you design a framework for testing microservices with REST Assured?
๐ Explanation
Microservices testing requires testing individual services in isolation and then testing service interactions. A well-designed framework handles both while managing the complexity of multiple services, environments, and authentication systems.
Framework Design Principles:
- Service-specific configuration โ Each microservice has its own base URI, authentication, and response specifications
- Contract testing โ JSON Schema validation ensures services communicate correctly
- Independent test suites โ Each service has its own test suite that can run independently
- Shared utilities โ Common code (auth, logging, reporting) is centralized
- Environment isolation โ Dev, staging, and production configurations are separate files
Framework Structure for Microservices:
src/ โโโ main/java/ โ โโโ framework/ โ โโโ services/ โ โ โโโ UserServiceClient.java โ โ โโโ OrderServiceClient.java โ โ โโโ PaymentServiceClient.java โ โโโ config/ โ โ โโโ UserServiceConfig.java โ โ โโโ OrderServiceConfig.java โ โโโ contract/ โ โโโ schemas/ โ โโโ user-response-schema.json โ โโโ order-response-schema.json
// Service Client Pattern
public class UserServiceClient {
private final RequestSpecification spec;
public UserServiceClient(String token) {
this.spec = new RequestSpecBuilder()
.setBaseUri(ConfigManager.getUserServiceUri())
.addHeader("Authorization", "Bearer " + token)
.addHeader("Content-Type", "application/json")
.setRelaxedHTTPSValidation()
.build();
}
public Response getUserById(int userId) {
return given()
.spec(spec)
.pathParam("id", userId)
.when()
.get("/users/{id}")
.then()
.statusCode(200)
.body(matchesJsonSchemaInClasspath("schemas/user-response-schema.json"))
.extract()
.response();
}
public Response createUser(UserRequest request) {
return given()
.spec(spec)
.body(request)
.when()
.post("/users")
.then()
.statusCode(201)
.extract()
.response();
}
}
Q37. How do you integrate REST Assured tests with CI/CD pipelines?
๐ Explanation
CI/CD integration is what transforms individual tests into a living quality gate. Every code change triggers the API test suite automatically, and failures block deployment until fixed.
๐ป GitHub Actions Pipeline:
name: API Tests
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
api-tests:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
java-version: '17'
distribution: 'temurin'
- name: Run API Tests against Staging
run: mvn test -Denv=staging -Dsurefire.suiteXmlFiles=testng.xml
env:
API_TOKEN: ${{ secrets.STAGING_API_TOKEN }}
BASE_URI: ${{ secrets.STAGING_BASE_URI }}
- name: Generate Allure Report
run: mvn allure:report
if: always()
- name: Upload Test Results
uses: actions/upload-artifact@v4
if: always()
with:
name: api-test-results
path: |
target/surefire-reports/
target/allure-report/
retention-days: 30
Q38. What is the difference between REST Assured and Postman for API testing?
| Aspect | REST Assured | Postman |
|---|---|---|
| Language | Java (code-based) | GUI + JavaScript |
| Coding skill required | Yes โ Java/TestNG | Minimal |
| CI/CD integration | Native โ Maven/Gradle | Via Newman CLI |
| Version control | Git-friendly (.java files) | JSON collections |
| Complex logic | Full Java power | JavaScript limited |
| Reusability | Excellent via OOP | Limited โ copy-paste |
| Reporting | Allure, Extent, TestNG | Built-in dashboard |
| Team collaboration | Code review via Git | Collection sharing |
| Data-driven testing | Excel, JSON, DB | CSV, JSON limited |
| Performance | Fast โ JVM | Slower โ Electron |
๐ฏ Interview Takeaway:
“Postman is excellent for API exploration and quick manual testing. REST Assured is the right choice when you need repeatable, maintainable, scalable automated API testing integrated with your existing Java test framework and CI/CD pipeline.”
Q39. How do you handle rate limiting in REST Assured tests?
๐ป Code Example
public class RateLimitHandler {
public static Response makeRequestWithRetry(
RequestSpecification spec,
String endpoint,
int maxRetries) {
for (int attempt = 0; attempt < maxRetries; attempt++) {
Response response = given()
.spec(spec)
.when()
.get(endpoint);
if (response.statusCode() == 429) {
// Rate limited โ wait and retry
String retryAfter = response.getHeader("Retry-After");
int waitSeconds = retryAfter != null ? Integer.parseInt(retryAfter) : 60;
System.out.println("Rate limited. Waiting " + waitSeconds + "s before retry...");
Thread.sleep(waitSeconds * 1000L);
continue;
}
return response; // Success or non-rate-limit error
}
throw new RuntimeException("Max retries exceeded for: " + endpoint);
}
}
Q40. How do you test pagination APIs with REST Assured?
๐ป Code Example
public class PaginationTest extends BaseTest {
@Test
public void testPaginationReturnsAllUsers() {
int page = 1;
int totalPages;
List<Integer> allUserIds = new ArrayList<>();
do {
Response response = given()
.spec(requestSpec)
.queryParam("page", page)
.queryParam("per_page", 6)
.when()
.get("https://reqres.in/api/users")
.then()
.statusCode(200)
.extract()
.response();
totalPages = response.jsonPath().getInt("total_pages");
List<Integer> pageUserIds = response.jsonPath().getList("data.id");
allUserIds.addAll(pageUserIds);
System.out.println("Page " + page + " users: " + pageUserIds);
page++;
} while (page <= totalPages);
System.out.println("Total users fetched: " + allUserIds.size());
// Verify no duplicate IDs across pages
Set<Integer> uniqueIds = new HashSet<>(allUserIds);
Assert.assertEquals(uniqueIds.size(), allUserIds.size(),
"Duplicate user IDs found across pages!");
}
}
7. REST Assured Interview Questions โ Scenario Based
These scenario-based REST Assured Interview Questions are increasingly common in senior interviews. They test your ability to apply knowledge to real-world problems.
Scenario Q1: An API that was working yesterday is now returning 500 errors in your test. How do you debug?
Answer:
Step 1 โ Enable full logging in REST Assured to capture the exact request being sent and the full response body:
given()
.log().all() // Log complete request
.when()
.get(endpoint)
.then()
.log().all(); // Log complete response
Step 2 โ Check if the API is actually down by testing it in Postman or curl independently.
Step 3 โ Compare the request you are sending with what the API expects โ headers, body format, authentication.
Step 4 โ Check if the issue is environment-specific by running the test against a different environment.
Step 5 โ Check CI/CD build logs for any recent changes to test data, endpoints, or authentication.
Scenario Q2: Your API tests pass locally but fail in CI/CD. What could cause this?
Answer:
Common causes and solutions:
- Environment configuration โ CI/CD uses different base URIs or API keys. Solution: Use environment variables in CI
- Authentication tokens โ Hardcoded tokens may be expired or environment-specific. Solution: Generate tokens dynamically
- Test data โ Data created locally may not exist in CI environment. Solution: Each test must create its own data
- Timing issues โ CI/CD machines may be slower. Solution: Increase timeouts in CI configuration
- SSL certificates โ CI environment may have different cert setup. Solution: Use
relaxedHTTPSValidation()in non-production
Scenario Q3: How do you test an API that requires a token obtained from a different API?
๐ป Code Example
public class TokenDependentTest extends BaseTest {
private String userToken;
@BeforeClass
public void obtainToken() {
userToken = given()
.contentType(ContentType.JSON)
.body("{ \"email\": \"eve.holt@reqres.in\", \"password\": \"cityslicka\" }")
.when()
.post("https://reqres.in/api/login")
.then()
.statusCode(200)
.extract()
.path("token");
Assert.assertNotNull(userToken, "Token must not be null");
System.out.println("Obtained token: " + userToken);
}
@Test
public void testProtectedEndpointWithToken() {
given()
.header("Authorization", "Token " + userToken)
.when()
.get("https://reqres.in/api/users")
.then()
.statusCode(200);
}
}
8. Common Mistakes Candidates Make in REST Assured Interviews
Understanding these mistakes โ and knowing how to avoid them โ separates prepared candidates from the rest.
Mistake 1: Using Thread.sleep() for waiting REST Assured tests should never use Thread.sleep(). The framework handles timing through connection timeouts and response timeouts. If an API is slow, configure connectionTimeout and responseTimeout in your spec.
Mistake 2: Hardcoding test data IDs, tokens, and timestamps hardcoded in tests will break when data changes. Always extract dynamic values from previous responses or generate them programmatically.
Mistake 3: Not validating status codes Validating only the response body without checking the status code means a 500 response with coincidentally matching body content could cause a false positive.
Mistake 4: Writing tests that depend on each other Each REST Assured test must be completely independent โ it must set up its own data, execute, validate, and clean up. Tests that depend on execution order are brittle and create debugging nightmares.
Mistake 5: Not using RequestSpecification Copy-pasting headers and base URIs across 50 test files is a maintainability disaster. Use RequestSpecification โ it is not optional in a real framework.
9. REST Assured Interview Questions โ Quick Revision Cheat Sheet
| Topic | Key Method |
|---|---|
| GET request | .get(url) |
| POST request | .post(url) with .body() |
| PUT request | .put(url) |
| DELETE request | .delete(url) |
| Status code | .statusCode(200) |
| Body validation | .body("field", equalTo(value)) |
| Header | .header("name", "value") |
| Query param | .queryParam("key", "value") |
| Path param | .pathParam("key", value) and {key} in URL |
| Basic Auth | .auth().basic("user", "pass") |
| Bearer Token | .header("Authorization", "Bearer " + token) |
| Extract value | .extract().path("field") |
| JSON Path | response.jsonPath().getString("field") |
| Schema validation | .body(matchesJsonSchemaInClasspath("schema.json")) |
| Response time | .time(lessThan(2000L)) |
| Logging | .log().all() |
| Reusable spec | RequestSpecBuilder โ given().spec(spec) |
| Base URI | RestAssured.baseURI = "https://..." |
| Content type | .contentType(ContentType.JSON) |
| File upload | .multiPart("file", file) |
10. What to Learn After These REST Assured Interview Questions
Now that you have covered all levels of REST Assured Interview Questions, here is your structured learning path:
Immediate next steps:
- Practice writing tests against real public APIs โ reqres.in, jsonplaceholder.typicode.com, petstore.swagger.io
- Build a complete framework with TestNG + REST Assured + Allure from scratch
- Implement the Page Object equivalent for APIs โ the Service Client pattern shown in Q36
Intermediate goals:
- Learn WireMock for API mocking and contract testing
- Master Pact for consumer-driven contract testing between microservices
- Integrate your framework with GitHub Actions or Jenkins
Advanced goals:
- Combine REST Assured API tests with Playwright UI tests in the same framework
- Learn GraphQL testing โ REST Assured can handle GraphQL queries via POST
- Explore performance testing integration โ trigger JMeter from your REST Assured framework
Final Conclusion
These 40+ REST Assured Interview Questions cover everything from the most basic beginner concepts to enterprise-level framework architecture. Mastering all levels of these REST Assured Interview Questions positions you as a well-rounded automation engineer who understands not just how to use the tool, but why each decision matters.
The most important thing to remember: REST Assured Interview Questions are not just about syntax. Interviewers want to see that you think like an engineer โ that you understand the principles behind the code, can design maintainable solutions, and can debug real problems under pressure.
Practice every code example in this guide against real APIs. Read the code, type it yourself, run it, break it, fix it. That practical experience is what converts knowledge of REST Assured Interview Questions into confident, fluent interview answers.
If this guide helped you, bookmark qatribe.in and share it with your network. More complete automation guides โ Playwright, TestNG, Cucumber, and Selenium โ are published regularly.
External Links:
1. Official REST Assured GitHub (Primary Source โ MUST HAVE)
2. REST Assured Official Website (Detailed Docs)
3. REST Assured Javadoc (Advanced / Interview Level )
4. Maven Dependency (Very Important for Setup Questions)
๐ฅ Continue Your Learning Journey
๐ Master TestNG Framework (Enterprise Level) Build scalable automation frameworks with CI/CD, parallel execution, and real-world architecture โก๏ธ Read: TestNG Automation Framework โ Complete Architect Guide
๐ Learn Cucumber (BDD from Scratch to Advanced) Understand Gherkin, step definitions, and real-world BDD framework design โก๏ธ Read: Cucumber Automation Framework โ Beginner to Advanced Guide
๐ API Authentication Made Simple Master JWT, OAuth, Bearer Tokens with real API testing examples โก๏ธ Read: Ultimate API Authentication Guide
๐ Crack Playwright Interviews (2026 Ready) Top real interview questions with answers and scenarios โก๏ธ Read: Playwright Interview Questions Guide