REST Assured Interview Questions: The Complete Guide (Beginner to Architect)
REST Assured Interview Questions: The Complete Guide (Beginner to Architect)
If you have an automation interview coming up, REST Assured Interview Questions are very important.There is a near-certain chance REST Assured will come up — not as a warm-up question, but as the centerpiece of the technical round.
API testing is no longer optional for QA engineers in 2026. With microservices dominating system design, every company — from Infosys and TCS to fast-growing product startups in Pune and Bangalore — expects you to write, debug, and design API tests from day one. REST Assured is the tool they test you on.
Most candidates prepare the wrong way. They memorise a list of definitions, walk into the interview, and then freeze when the interviewer says: “Show me how you’d design a scalable REST Assured framework for a CI/CD pipeline.” Definitions don’t answer that. Experience does.
This guide covers 50+ real interview questions — the same ones asked in actual technical rounds — with answers written the way you should deliver them out loud, not just read them on a screen. It goes from absolute basics all the way to architect-level framework design, CI/CD integration, and scenario-based questions that trip up experienced engineers.
Whether you are appearing for your first automation role or targeting a senior SDET position, by the end of this guide you will be able to confidently handle any REST Assured question thrown at you.
Table of Contents
- Why REST Assured Dominates Automation Interviews
- REST Assured Fundamentals — What Every Interview Starts With
- Questions 1–20 — Beginner Level
- Questions 21–35 — Intermediate Level
- Questions 36–40 — Advanced Level
- Questions 41–50 — Architect & Framework Design
- Scenario-Based Questions
- Common Mistakes Candidates Make
- Quick Revision Cheat Sheet
- What to Learn Next
1. Why REST Assured Dominates Automation Interviews
Before the questions, understand why this topic appears in every serious interview in 2026.
API testing has shifted from a “nice to have” to a core mandatory skill for every QA automation role. Modern applications are built on microservices where hundreds of services communicate 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 things simultaneously:
Conceptual clarity — Do you understand what you are doing and why? “What is the difference between queryParam and pathParam?” is not just a syntax question. Interviewers want to know if you understand how URLs are structured.
Hands-on coding ability — Can you write REST Assured code without looking at documentation? Almost every interview includes a live coding component. Knowing the API by heart is non-negotiable.
Framework thinking — Can you scale REST Assured beyond individual tests into a maintainable, reusable framework? Senior questions focus almost entirely on RequestSpecification, ResponseSpecification, data-driven approaches, and CI/CD integration.
Companies like Infosys, TCS, Wipro, Cognizant, and every major product company hiring in Pune, Bangalore, Hyderabad, and Chennai include REST Assured as a standard filter. Candidates who master it clear technical rounds that eliminate 70% of applicants.
2. REST Assured Fundamentals
Before any questions, lock these fundamentals in memory. Interviewers use them as warm-up questions, and a weak answer here signals a weak candidate before the real questions begin.
What is REST Assured?
REST Assured is an open-source Java-based library for testing and validating RESTful web services, created by Johan Haleby. It abstracts the complexity of HTTP communication behind a fluent, readable DSL (Domain Specific Language).
Before REST Assured, testing APIs in Java required 30–50 lines of boilerplate with Apache HttpClient. REST Assured reduces that to 3–5 lines.
Why is REST Assured the Industry Standard?
- Zero boilerplate for common operations — a complete GET request with validation is three lines
- Built-in JSON and XML parsing without extra libraries
- Integrates with TestNG, JUnit 4, and JUnit 5
- Supports every auth mechanism: Basic Auth, OAuth 1.0/2.0, Bearer tokens, API keys, Digest Auth
- Built-in request/response logging, critical for CI/CD debugging
- Hamcrest matcher integration for expressive, readable assertions
Maven Dependency — Always Have This Ready
Every interview may begin with “How do you add REST Assured to your project?” — have this memorised:
xml
<!-- REST Assured Core -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</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>
<!-- JSON Schema Validator -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>5.4.0</version>
</dependency>
<!-- TestNG -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.8.0</version>
<scope>test</scope>
</dependency>3. Beginner Level — Questions 1–20
These are the questions you will face in every first-round screening interview. Answer all of these confidently and completely.
Q1. What is REST Assured and why is it used in API testing?
Explanation
REST Assured is a Java DSL library built specifically for testing RESTful web services. It supports all HTTP methods, handles JSON and XML parsing out of the box, and integrates with every major Java testing framework.
The BDD-style syntax — given(), when(), then() — mirrors Gherkin language, making REST Assured tests self-documenting and readable by non-technical stakeholders.
Code Example
java
import io.restassured.RestAssured;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
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
“REST Assured follows Given-When-Then from BDD, which means even non-technical stakeholders can read our API tests. This is a significant advantage in Agile teams.”
Q2. What are the main features of REST Assured?
Explanation
- BDD-style syntax —
given(),when(),then()makes tests readable and self-documenting - Built-in assertions — Hamcrest matchers for status codes, headers, response body, and response time
- JSON and XML support — JsonPath and XmlPath included out of the box
- Authentication support — Basic Auth, Digest Auth, OAuth 1.0/2.0, Bearer tokens, form auth
- Request/Response logging — granular logging control including log-on-failure only
- Schema validation — validate JSON responses against a JSON Schema for contract testing
- RequestSpecification / ResponseSpecification — reusable configurations eliminating duplication
Code Example
java
given()
.header("Content-Type", "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));Q3. How do you send a GET request using REST Assured?
Explanation
GET requests retrieve data without modifying anything on the server. In REST Assured, use the get() method inside when(). They can include query parameters and path parameters but never a request body.
Always set baseURI globally rather than hardcoding the full URL in every test — this makes switching environments a single line change.
Code Example
java
RestAssured.baseURI = "https://reqres.in";
// Simple GET
given()
.when()
.get("/api/users/2")
.then()
.statusCode(200);
// GET with query parameters
given()
.queryParam("page", 2)
.queryParam("per_page", 6)
.when()
.get("/api/users")
.then()
.statusCode(200)
.body("page", equalTo(2));
// GET with path parameter
given()
.pathParam("userId", 3)
.when()
.get("/api/users/{userId}")
.then()
.statusCode(200)
.body("data.id", equalTo(3));Q4. How do you validate the response status code?
Explanation
Status code validation is mandatory in every API test. It confirms the API processed your request as expected. Use statusCode() in the then() block.
Important patterns by code range:
- 2xx — Success (200 OK, 201 Created, 204 No Content)
- 4xx — Client error (400 Bad Request, 401 Unauthorized, 404 Not Found)
- 5xx — Server error (500 Internal Server Error)
Always validate status code first — a 500 response can still return a JSON body, and without this check your test might incorrectly pass.
Code Example
java
// 200 OK
given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.statusCode(200);
// 201 Created
given()
.contentType("application/json")
.body("{ \"name\": \"Ajit\", \"job\": \"QA Lead\" }")
.when()
.post("https://reqres.in/api/users")
.then()
.statusCode(201);
// 404 Not Found
given()
.when()
.get("https://reqres.in/api/users/999")
.then()
.statusCode(404);
// Flexible validation with Hamcrest
given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.statusCode(anyOf(is(200), is(201)));Q5. What is the difference between given(), when(), and then()?
Explanation
This tests both your library knowledge and your understanding of BDD principles.
- given() — Setup phase: headers, query params, path params, request body, auth, content type, base URI, logging, SSL config
- when() — Action phase: specify the HTTP method (
get(),post(),put(),delete(),patch()) - then() — Validation phase: status code, body assertions, headers, response time, content type
This separation improves readability, maintainability, and aligns tests with business-readable scenarios.
Code Example
java
given()
.header("Authorization", "Bearer " + token)
.contentType("application/json")
.body("{ \"name\": \"Ajit\" }")
.when()
.post("https://reqres.in/api/users")
.then()
.statusCode(201)
.body("name", equalTo("Ajit"));Q6. How do you add query parameters?
Explanation
Query parameters filter or customise API responses. Use queryParam() — they are appended to the URL after ?. Commonly used in search, pagination, and filtering.
java
given()
.queryParam("page", 2)
.queryParam("per_page", 5)
.when()
.get("https://reqres.in/api/users")
.then()
.statusCode(200)
.body("page", equalTo(2));Q7. How do you send path parameters?
Explanation
Path parameters are dynamic values embedded in the URL path. Use pathParam() to define them, and use {placeholders} in the endpoint. This avoids hardcoding and improves reusability.
java
given()
.pathParam("id", 2)
.when()
.get("https://reqres.in/api/users/{id}")
.then()
.statusCode(200)
.body("data.id", equalTo(2));Q8. How do you validate the response body?
Explanation
Response body validation uses Hamcrest matchers to verify JSON or XML fields. This is critical for confirming business logic, not just success status.
java
given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.body("data.id", equalTo(2))
.body("data.first_name", equalTo("Janet"))
.body("data.last_name", notNullValue());Q9. How do you parse a JSON response?
Explanation
jsonPath() navigates JSON structures to extract specific values. This is essential for chaining API calls where one response feeds the next request, eliminating dependency on hardcoded values.
java
// Method 1 — Response object
Response response = get("https://reqres.in/api/users/2");
String firstName = response.jsonPath().getString("data.first_name");
List<Integer> ids = response.jsonPath().getList("data.id");
// Method 2 — Inline extract
String email =
given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.extract()
.path("data.email");
// Method 3 — GPath filter (interview favourite)
String user =
given()
.when()
.get("https://jsonplaceholder.typicode.com/users")
.then()
.extract()
.path("find { it.id == 5 }.username");Q10. What is the Response object?
Explanation
The Response object holds the complete API response — status code, headers, and body. It allows multiple extractions and validations, and is essential in complex scenarios like token extraction or chained API calls.
java
Response response = get("https://reqres.in/api/users/2");
int statusCode = response.getStatusCode();
String body = response.getBody().asString();
String contentType = response.getContentType();
String userId = response.jsonPath().getString("data.id");Q11. How do you handle headers?
Explanation
Headers carry metadata like auth tokens and content type. Use header() to add them. Multiple headers can be chained. Critical for secured APIs and content negotiation.
java
given()
.header("Authorization", "Bearer " + token)
.header("Accept", "application/json")
.header("X-Custom-Header", "value")
.when()
.get("https://reqres.in/api/users");Q12. How do you perform a POST request with a JSON body?
Explanation
POST creates new resources. Pass JSON using .body() and set contentType("application/json"). The expected response is usually 201 Created.
java
String requestBody = "{ \"name\": \"Ajit Marathe\", \"job\": \"QA Lead\" }";
given()
.contentType("application/json")
.body(requestBody)
.when()
.post("https://reqres.in/api/users")
.then()
.statusCode(201)
.body("name", equalTo("Ajit Marathe"))
.body("id", notNullValue());Q13. What is Content-Type and how do you set it?
Explanation
Content-Type specifies the format of the request body. It is mandatory for POST and PUT requests. Incorrect Content-Type causes parsing failures on the server side.
java
// Using string
given().contentType("application/json");
// Using ContentType enum (preferred)
given().contentType(ContentType.JSON);
given().contentType(ContentType.XML);Q14. How do you log requests and responses?
Explanation
Logging is essential for debugging failed tests, especially in CI/CD pipelines. REST Assured provides granular control — you can log everything or only on failure.
java
// Log everything
given()
.log().all()
.when()
.get("https://reqres.in/api/users")
.then()
.log().all()
.statusCode(200);
// Log only when test fails (preferred for production frameworks)
given()
.log().ifValidationFails()
.when()
.get("https://reqres.in/api/users")
.then()
.log().ifValidationFails()
.statusCode(200);Interview Takeaway: “In production frameworks I use log().ifValidationFails() to keep CI logs clean. Full logging is reserved for local debugging.”
Q15. How do you validate response time?
Explanation
Response time validation ensures APIs meet SLA requirements. Use time() with Hamcrest matchers. Combine with functional assertions for complete test coverage.
java
given()
.when()
.get("https://reqres.in/api/users")
.then()
.statusCode(200)
.time(lessThan(2000L)); // Must respond within 2 secondsQ16. What is Hamcrest and how does it work with REST Assured?
Explanation
Hamcrest is an assertion library providing readable matcher methods. It is deeply integrated into REST Assured for body validation.
Common matchers:
| Matcher | Use |
|---|---|
equalTo(x) | Exact match |
not(x) | Negation |
notNullValue() | Not null |
containsString(x) | String contains |
hasItem(x) | List contains item |
hasSize(n) | Collection size |
greaterThan(n) | Numeric comparison |
lessThan(n) | Numeric comparison |
anyOf(a, b) | Either condition |
allOf(a, b) | Both conditions |
java
given()
.when()
.get("https://reqres.in/api/users")
.then()
.body("data.size()", greaterThan(0))
.body("data.first_name", hasItem("Janet"))
.body("total", notNullValue());Q17. How do you extract values from a response?
Explanation
Extracted values are reused in subsequent API calls — for example, extracting a created user’s ID for a follow-up GET or DELETE test. This is essential for chaining APIs in end-to-end test flows.
java
// Extract single value
String userId =
given()
.contentType("application/json")
.body("{ \"name\": \"Ajit\" }")
.when()
.post("https://reqres.in/api/users")
.then()
.statusCode(201)
.extract()
.path("id");
// Extract full response for multiple uses
Response response =
given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.extract()
.response();
String email = response.path("data.email");
int id = response.path("data.id");Q18. How do you reuse request specification (RequestSpecification)?
Explanation
RequestSpecification defines reusable configurations — base URI, headers, auth — that are shared across all tests. This eliminates duplication and ensures consistency. It is a best practice in any production framework.
java
RequestSpecification requestSpec = new RequestSpecBuilder()
.setBaseUri("https://reqres.in")
.setContentType(ContentType.JSON)
.addHeader("Authorization", "Bearer " + token)
.log(LogDetail.ALL)
.build();
// Reuse across tests
given()
.spec(requestSpec)
.when()
.get("/api/users/2")
.then()
.statusCode(200);
given()
.spec(requestSpec)
.body("{ \"name\": \"Ajit\" }")
.when()
.post("/api/users")
.then()
.statusCode(201);Q19. What is baseURI and how do you configure it?
Explanation
baseURI is the root endpoint for all API requests. Setting it globally avoids repeating the full URL in every test and enables easy environment switching — just change one line.
java
// Global configuration (in @BeforeSuite or base test class)
RestAssured.baseURI = "https://reqres.in";
RestAssured.basePath = "/api";
RestAssured.port = 443;
// Now all tests use this base automatically
given()
.when()
.get("/users/2") // Resolves to https://reqres.in/api/users/2
.then()
.statusCode(200);Q20. How do you handle all HTTP methods?
Explanation
REST Assured supports all HTTP methods directly. Understanding when to use each is fundamental:
java
// GET — retrieve
given().when().get("/api/users").then().statusCode(200);
// POST — create
given().contentType(ContentType.JSON)
.body("{ \"name\": \"Ajit\" }")
.when().post("/api/users").then().statusCode(201);
// PUT — full update (replaces entire resource)
given().contentType(ContentType.JSON)
.body("{ \"name\": \"Ajit\", \"job\": \"Senior QA\" }")
.when().put("/api/users/2").then().statusCode(200);
// PATCH — partial update (only what changed)
given().contentType(ContentType.JSON)
.body("{ \"job\": \"Architect\" }")
.when().patch("/api/users/2").then().statusCode(200);
// DELETE — remove
given().when().delete("/api/users/2").then().statusCode(204);Interview Takeaway: “The key difference between PUT and PATCH is that PUT replaces the entire resource while PATCH updates only the specified fields. This matters because accidentally using PUT can wipe fields you didn’t intend to change.”
4. Intermediate Level — Questions 21–35
These questions appear in second-round technical interviews and test your practical depth.
Q21. How do you handle authentication in REST Assured?
Explanation
REST Assured supports multiple authentication mechanisms natively. The approach depends on what the API requires.
java
// Basic Authentication
given()
.auth().basic("username", "password")
.when()
.get("/api/protected");
// Bearer Token (OAuth 2.0 / JWT)
given()
.header("Authorization", "Bearer " + accessToken)
.when()
.get("/api/protected");
// OAuth 2.0 with token extraction
String token =
given()
.contentType("application/x-www-form-urlencoded")
.formParam("grant_type", "client_credentials")
.formParam("client_id", clientId)
.formParam("client_secret", clientSecret)
.when()
.post("/oauth/token")
.then()
.statusCode(200)
.extract()
.path("access_token");
// Preemptive Basic Auth (sends credentials without waiting for 401)
given()
.auth().preemptive().basic("username", "password")
.when()
.get("/api/users");Q22. How do you perform JSON Schema Validation?
Explanation
JSON Schema Validation confirms that the API response structure matches a defined contract — not just the values, but the shape of the response. This is critical for microservices contract testing. Add json-schema-validator to your Maven dependencies.
java
// user-schema.json (place in src/test/resources)
// {
// "$schema": "http://json-schema.org/draft-07/schema#",
// "type": "object",
// "properties": {
// "data": {
// "type": "object",
// "properties": {
// "id": { "type": "integer" },
// "email": { "type": "string" },
// "first_name": { "type": "string" }
// },
// "required": ["id", "email", "first_name"]
// }
// }
// }
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.statusCode(200)
.body(matchesJsonSchemaInClasspath("user-schema.json"));Q23. How do you handle cookies in REST Assured?
java
// Add cookie to request
given()
.cookie("session_id", "abc123")
.cookie("user_pref", "dark_mode")
.when()
.get("/api/dashboard");
// Extract cookie from response
String sessionCookie =
given()
.contentType("application/json")
.body("{ \"email\": \"user@example.com\", \"password\": \"pass\" }")
.when()
.post("/api/login")
.then()
.extract()
.cookie("session_id");
// Use extracted cookie in subsequent request
given()
.cookie("session_id", sessionCookie)
.when()
.get("/api/profile");Q24. How do you test file upload APIs?
java
given()
.contentType("multipart/form-data")
.multiPart("file", new File("src/test/resources/test-document.pdf"))
.multiPart("description", "Test file upload")
.multiPart("category", "documents")
.when()
.post("https://api.example.com/upload")
.then()
.statusCode(200)
.body("filename", notNullValue())
.body("size", greaterThan(0));Q25. How do you handle SSL/HTTPS in REST Assured?
Explanation
For non-production environments with self-signed certificates, REST Assured lets you relax SSL validation. Never use this in production tests.
java
// Disable SSL validation (for testing environments only)
given()
.relaxedHTTPSValidation()
.when()
.get("https://self-signed-cert-api.example.com/api/users");
// Global SSL relaxation for all tests
RestAssured.useRelaxedHTTPSValidation();Q26. How do you implement data-driven testing?
Explanation
Data-driven testing runs the same test logic with multiple data sets. Use TestNG’s @DataProvider to feed data to REST Assured tests.
java
@DataProvider(name = "userCredentials")
public Object[][] provideCredentials() {
return new Object[][] {
{"admin@company.com", "admin123", 200},
{"user@company.com", "user456", 200},
{"invalid@company.com", "wrongpass", 401},
{"", "", 400}
};
}
@Test(dataProvider = "userCredentials")
public void testLoginWithMultipleCredentials(String email, String password, int expectedStatus) {
given()
.contentType("application/json")
.body("{ \"email\": \"" + email + "\", \"password\": \"" + password + "\" }")
.when()
.post("https://reqres.in/api/login")
.then()
.statusCode(expectedStatus);
}Q27. What is ResponseSpecification and how do you use it?
Explanation
ResponseSpecification defines reusable validation rules — just like RequestSpecification does for requests. Useful when many tests share the same expected response shape.
java
ResponseSpecification responseSpec = new ResponseSpecBuilder()
.expectStatusCode(200)
.expectContentType(ContentType.JSON)
.expectResponseTime(lessThan(3000L))
.build();
// Reuse across tests
given()
.spec(requestSpec)
.when()
.get("/api/users/2")
.then()
.spec(responseSpec)
.body("data.id", equalTo(2));Q28. How do you handle XML responses?
java
given()
.when()
.get("https://api.example.com/users/1.xml")
.then()
.statusCode(200)
.contentType(ContentType.XML)
.body("user.id", equalTo("1"))
.body("user.name", equalTo("Ajit"));
// Extract XML values
Response response = given().when().get("https://api.example.com/users");
String userName = response.xmlPath().getString("users.user[0].name");
List<String> allNames = response.xmlPath().getList("users.user.name");Q29. How do you use filters in REST Assured?
Explanation
Filters intercept every request and response. They are used for logging, adding headers globally, or monitoring performance across the entire test suite.
java
// Custom logging filter
RestAssured.filters(new RequestLoggingFilter(), new ResponseLoggingFilter());
// Custom filter for adding auth header to every request
RestAssured.filters((requestSpec, responseSpec, ctx) -> {
requestSpec.header("X-Request-ID", UUID.randomUUID().toString());
return ctx.next(requestSpec, responseSpec);
});Q30. How do you mock API responses in REST Assured tests?
Explanation
WireMock is the standard tool for API mocking in Java. Use it when the real API is unavailable, unstable, or too slow for unit testing.
java
// Setup WireMock server
WireMockServer wireMockServer = new WireMockServer(8080);
wireMockServer.start();
wireMockServer.stubFor(
get(urlEqualTo("/api/users/1"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{ \"id\": 1, \"name\": \"Ajit Marathe\" }"))
);
// Test against mock
given()
.when()
.get("http://localhost:8080/api/users/1")
.then()
.statusCode(200)
.body("name", equalTo("Ajit Marathe"));
wireMockServer.stop();Q31. How do you chain API calls in REST Assured?
Explanation
Chaining means extracting a value from one API response and using it in the next call. This is the core of end-to-end API test flows.
java
// Step 1: Create user and capture the returned ID
String userId =
given()
.contentType("application/json")
.body("{ \"name\": \"Ajit Marathe\", \"job\": \"QA Lead\" }")
.when()
.post("https://reqres.in/api/users")
.then()
.statusCode(201)
.extract()
.path("id");
// Step 2: Use the ID in a follow-up request
given()
.pathParam("id", userId)
.when()
.get("https://reqres.in/api/users/{id}")
.then()
.statusCode(200);
// Step 3: Delete the created user
given()
.pathParam("id", userId)
.when()
.delete("https://reqres.in/api/users/{id}")
.then()
.statusCode(204);Q32. How do you handle dynamic tokens?
Explanation
In most real frameworks, the auth token must be fetched once per test suite, then shared across all tests. Storing it in a static field set during @BeforeSuite is the standard approach.
java
public class BaseTest {
protected static String authToken;
@BeforeSuite
public void setupAuth() {
authToken =
given()
.contentType("application/json")
.body("{ \"email\": \"eve.holt@reqres.in\", \"password\": \"cityslicka\" }")
.when()
.post("https://reqres.in/api/login")
.then()
.statusCode(200)
.extract()
.path("token");
}
}
public class UserTests extends BaseTest {
@Test
public void getUser() {
given()
.header("Authorization", "Bearer " + authToken)
.when()
.get("https://reqres.in/api/users/2")
.then()
.statusCode(200);
}
}Q33. How do you integrate REST Assured with Allure reporting?
xml
<!-- Add to pom.xml -->
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-testng</artifactId>
<version>2.25.0</version>
</dependency>java
@Epic("User Management")
@Feature("User API")
public class UserApiTests {
@Test
@Story("Get user by ID")
@Description("Validate that fetching user by ID returns correct data")
@Severity(SeverityLevel.CRITICAL)
public void getUserById() {
given()
.filter(new AllureRestAssured()) // Attaches request/response to Allure report
.when()
.get("https://reqres.in/api/users/2")
.then()
.statusCode(200)
.body("data.id", equalTo(2));
}
}Q34. How do you run REST Assured tests in parallel?
xml
<!-- testng.xml -->
<suite name="API Tests" parallel="methods" thread-count="5">
<test name="User API Tests">
<classes>
<class name="com.qatribe.tests.UserApiTests"/>
</classes>
</test>
</suite>java
// BaseTest with thread-safe RequestSpecification
public class BaseTest {
protected ThreadLocal<RequestSpecification> requestSpec = new ThreadLocal<>();
@BeforeMethod
public void setup() {
requestSpec.set(new RequestSpecBuilder()
.setBaseUri("https://reqres.in")
.setContentType(ContentType.JSON)
.build());
}
}Q35. How do you implement retry logic for flaky API tests?
java
// TestNG retry analyzer
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++;
return true;
}
return false;
}
}
// Apply to test
@Test(retryAnalyzer = RetryAnalyzer.class)
public void testFlakyApiEndpoint() {
given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.statusCode(200);
}5. Advanced Level — Questions 36–40
These questions are asked in third rounds and senior SDET interviews.
Q36. How do you design a complete API Testing Framework with REST Assured?
Explanation
A production-ready REST Assured framework has a clear layered structure:
src/ ├── test/ │ ├── java/ │ │ ├── base/ │ │ │ └── BaseTest.java (RestAssured config, auth setup) │ │ ├── config/ │ │ │ └── ConfigManager.java (environment config from properties files) │ │ ├── endpoints/ │ │ │ └── UserEndpoints.java (API endpoint constants) │ │ ├── models/ │ │ │ ├── UserRequest.java (POJO for request body) │ │ │ └── UserResponse.java (POJO for response) │ │ ├── tests/ │ │ │ └── UserApiTests.java (actual test classes) │ │ └── utils/ │ │ ├── AuthUtils.java (token handling) │ │ └── TestDataUtils.java (test data generation) │ └── resources/ │ ├── config.properties (base URLs, credentials) │ ├── test-data/ (JSON payloads, CSV data) │ └── schemas/ (JSON schemas for validation)
Key principle: Tests should contain only assertions. All configuration, auth, and request setup belongs in the base layer.
JSON Schema validator
Q37. How do you integrate REST Assured with CI/CD?
yaml
# GitHub Actions example
name: API Tests
on: [push, pull_request]
jobs:
api-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
- name: Run API Tests
run: mvn test -Denv=staging -Dgroups=smoke
env:
API_TOKEN: ${{ secrets.API_TOKEN }}
- name: Generate Allure Report
run: mvn allure:report
- name: Upload Report
uses: actions/upload-artifact@v3
with:
name: allure-report
path: target/site/allure-maven-pluginjava
// Environment-aware configuration
public class ConfigManager {
private static Properties props = new Properties();
static {
String env = System.getProperty("env", "staging");
try (InputStream is = ConfigManager.class
.getResourceAsStream("/config-" + env + ".properties")) {
props.load(is);
} catch (IOException e) {
throw new RuntimeException("Cannot load config for env: " + env);
}
}
public static String getBaseUri() {
return props.getProperty("base.uri");
}
}Q38. What is the difference between REST Assured and Postman?
| Aspect | REST Assured | Postman |
|---|---|---|
| Language | Java code | GUI + JavaScript |
| CI/CD integration | Native — runs in any Maven/Gradle pipeline | Requires Newman CLI |
| Version control | Full Git support | Collections as JSON, less readable |
| Data-driven testing | Native via TestNG @DataProvider | Limited built-in support |
| Framework design | Full OOP — reusable specs, base classes | Limited reusability |
| Learning curve | Higher (requires Java) | Lower (GUI-based) |
| Best for | Large-scale automated regression | Exploratory testing, quick checks |
Interview Takeaway: “I use Postman for exploratory testing and quick validation during development. For automated regression that runs in CI/CD, REST Assured is the right choice — it integrates with the existing Java ecosystem and version-controlled properly.”
Q39. How do you handle rate limiting in REST Assured tests?
java
public class RateLimitHandler {
public Response executeWithRetry(String endpoint, int maxRetries) {
int attempt = 0;
while (attempt < maxRetries) {
Response response = given().when().get(endpoint);
if (response.getStatusCode() == 429) {
// Respect the server's Retry-After header
int retryAfter = Integer.parseInt(
response.getHeader("Retry-After") != null
? response.getHeader("Retry-After")
: "60"
);
try {
Thread.sleep(retryAfter * 1000L);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
attempt++;
} else {
return response;
}
}
throw new RuntimeException("Max retries exceeded for: " + endpoint);
}
}Q40. How do you test pagination APIs?
java
@Test
public void testCompletePagination() {
int currentPage = 1;
int totalPages;
List<Integer> allUserIds = new ArrayList<>();
do {
Response response =
given()
.queryParam("page", currentPage)
.queryParam("per_page", 6)
.when()
.get("https://reqres.in/api/users")
.then()
.statusCode(200)
.extract()
.response();
totalPages = response.path("total_pages");
List<Integer> pageIds = response.jsonPath().getList("data.id");
allUserIds.addAll(pageIds);
currentPage++;
} while (currentPage <= totalPages);
// Validate no duplicate IDs across pages
Set<Integer> uniqueIds = new HashSet<>(allUserIds);
assertEquals(uniqueIds.size(), allUserIds.size(), "Duplicate IDs found across pages");
System.out.println("Total users fetched across all pages: " + allUserIds.size());
}6. Architect Level — Questions 41–50
These questions distinguish senior engineers from the rest.
Q41. How do you design a framework for testing microservices?
Explanation
Testing microservices requires a framework that handles independent service authentication, service-to-service contract validation, and the ability to run tests against individual services in isolation.
java
public abstract class MicroserviceBaseTest {
protected RequestSpecification userServiceSpec;
protected RequestSpecification orderServiceSpec;
protected RequestSpecification paymentServiceSpec;
@BeforeSuite
public void initializeServiceSpecs() {
String userToken = AuthUtils.getServiceToken("user-service");
String orderToken = AuthUtils.getServiceToken("order-service");
userServiceSpec = new RequestSpecBuilder()
.setBaseUri(ConfigManager.get("user.service.url"))
.addHeader("Authorization", "Bearer " + userToken)
.setContentType(ContentType.JSON)
.build();
orderServiceSpec = new RequestSpecBuilder()
.setBaseUri(ConfigManager.get("order.service.url"))
.addHeader("Authorization", "Bearer " + orderToken)
.setContentType(ContentType.JSON)
.build();
}
}Q42. How do you implement contract testing with REST Assured?
Explanation
Contract testing ensures that both the API producer (server) and consumer (client) agree on the request/response structure. This prevents integration failures when services are updated independently.
java
// Consumer contract test — validates the API matches what the consumer expects
@Test
public void validateUserApiContract() {
given()
.when()
.get("https://reqres.in/api/users/2")
.then()
.statusCode(200)
// Validate structure via JSON Schema
.body(matchesJsonSchemaInClasspath("schemas/user-response-schema.json"))
// Validate required fields exist and are correct types
.body("data.id", instanceOf(Integer.class))
.body("data.email", matchesPattern("^[\\w.-]+@[\\w.-]+\\.[a-z]{2,}$"))
.body("data.first_name", instanceOf(String.class));
}Q43. How do you implement environment-based configuration?
java
// config-dev.properties
// base.uri=https://dev-api.company.com
// auth.url=https://dev-auth.company.com
// config-staging.properties
// base.uri=https://staging-api.company.com
// auth.url=https://staging-auth.company.com
public class EnvironmentConfig {
private static final String ENV = System.getProperty("env", "staging");
private static Properties props;
static {
try (InputStream is = EnvironmentConfig.class
.getResourceAsStream("/config-" + ENV + ".properties")) {
props = new Properties();
props.load(is);
} catch (IOException e) {
throw new RuntimeException("Failed to load environment config: " + ENV);
}
}
public static String getBaseUri() { return props.getProperty("base.uri"); }
public static String getAuthUrl() { return props.getProperty("auth.url"); }
}Run specific environment: mvn test -Denv=staging
Q44. How do you use POJOs (Plain Old Java Objects) with REST Assured?
Explanation
Using POJOs instead of raw JSON strings makes request building type-safe and eliminates JSON formatting errors. Jackson handles serialization/deserialization automatically.
java
// Request POJO
@JsonIgnoreProperties(ignoreUnknown = true)
public class CreateUserRequest {
private String name;
private String job;
// getters, setters, constructors
}
// Response POJO
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserResponse {
private UserData data;
// getters, setters
}
// Using POJOs in tests
CreateUserRequest request = new CreateUserRequest("Ajit Marathe", "QA Architect");
UserResponse response =
given()
.contentType(ContentType.JSON)
.body(request)
.when()
.post("https://reqres.in/api/users")
.then()
.statusCode(201)
.extract()
.as(UserResponse.class);
assertEquals(response.getData().getName(), "Ajit Marathe");Q45–50. Quick-Fire Architect Questions
Q45. How do you measure API test coverage? Track coverage by HTTP method, endpoint, status code, and error scenarios. Use a test management tool like Xray or Zephyr linked to your JIRA tickets. Every documented API endpoint should have at minimum a happy path test and at least two negative tests.
Q46. How do you handle flaky tests in a large REST Assured suite? First classify whether flakiness is in the test code or the API itself. For test code issues: add proper waits, use retry logic sparingly. For API instability: use WireMock to mock the unstable dependency and file a bug against the API team.
Q47. How do you ensure REST Assured test isolation? Each test should create its own test data (not depend on data left by previous tests), clean up after itself, and not share mutable state. Use @BeforeMethod for setup and @AfterMethod for cleanup.
Q48. What is the difference between extract().path() and jsonPath().get()? extract().path() is used inline in the fluent chain after then(). jsonPath().get() is used on a Response object after the fact. Both achieve the same result — choose based on what is more readable in context.
Q49. How do you test GraphQL APIs with REST Assured? GraphQL APIs use POST requests with a JSON body containing a query field. REST Assured handles them identically to REST APIs:
java
String graphqlQuery = "{ \"query\": \"{ users { id name email } }\" }";
given()
.contentType("application/json")
.body(graphqlQuery)
.when()
.post("https://api.example.com/graphql")
.then()
.statusCode(200)
.body("data.users.size()", greaterThan(0));Q50. How do you handle token expiry in long-running test suites? Implement a token manager with expiry tracking. Before each request, check if the token is within 60 seconds of expiry and refresh if needed. Store the token and expiry timestamp as static fields in a thread-safe singleton.
7. Scenario-Based Questions
These are asked in senior interviews to test real-world problem solving.
Scenario 1: An API that worked yesterday now returns 500 errors. How do you debug?
- Check logs first — add
log().all()to capture full request and response including headers - Isolate the environment — does it fail in all environments or just one? Staging config issue vs code issue
- Test in Postman — remove REST Assured from the equation to confirm whether the API itself is broken
- Check recent changes — was the API contract changed? Use JSON schema validation to catch structural differences
- Check auth — has the token expired? Is the endpoint now requiring a different scope?
- Compare headers — use
response.getHeaders()to compare what headers the server is returning now vs before
Scenario 2: Tests pass locally but fail in CI/CD. What is causing it?
The most common causes:
- Environment differences — local uses dev/localhost, CI hits staging. Check
baseURIand environment config - Hardcoded credentials — passwords or tokens committed to code that don’t work in CI. Move to environment variables or CI secrets
- Timing issues — local runs wait for the same JVM warm-up, CI is fresh. Add explicit response time validation
- SSL certificates — staging may have a self-signed cert that fails strict SSL validation. Add
relaxedHTTPSValidation()for staging only - Test order dependency — CI may run tests in a different order. Ensure each test is fully independent
Scenario 3: How do you test an API that requires a token from a different API?
java
public class TokenChainTest {
@Test
public void testWithDynamicToken() {
// Step 1: Get auth token
String token =
given()
.contentType("application/json")
.body("{ \"email\": \"eve.holt@reqres.in\", \"password\": \"cityslicka\" }")
.when()
.post("https://reqres.in/api/login")
.then()
.statusCode(200)
.extract()
.path("token");
// Step 2: Use token in protected endpoint
given()
.header("Authorization", "Bearer " + token)
.when()
.get("https://reqres.in/api/users/2")
.then()
.statusCode(200)
.body("data.id", equalTo(2));
}
}8. Common Mistakes Candidates Make
These mistakes appear repeatedly in interviews and cost candidates the offer:
1. Keyword stuffing in answers — Saying “REST Assured Interview Questions” in every sentence signals you memorised a blog, not that you understand the tool. Speak like a practitioner.
2. No mention of framework design — For any role above junior, the interviewer expects to hear about RequestSpecification, base test classes, and environment configuration. Not knowing these signals you have only ever written throwaway scripts.
3. Confusing put() and patch() — PUT replaces the entire resource. PATCH updates specific fields. Getting this wrong is a basic mistake that immediately flags a candidate.
4. No error handling in framework code — Production frameworks handle token expiry, rate limits, and retries gracefully. Showing awareness of this separates senior engineers from mid-level.
5. Hardcoding URLs and credentials — If your code examples have https://prod-api.company.com and actual passwords, interviewers will notice and mark you down for security awareness.
6. Ignoring response time validation — Performance testing is part of API testing. Always mention time(lessThan(3000L)) and SLA awareness.
9. Quick Revision Cheat Sheet
| Task | Method |
|---|---|
| Set base URI | RestAssured.baseURI = "https://api.example.com" |
| GET request | .when().get("/endpoint") |
| POST with JSON | .contentType(JSON).body(payload).when().post("/endpoint") |
| Validate status | .then().statusCode(200) |
| Validate body field | .then().body("field.path", equalTo(value)) |
| Extract value | .then().extract().path("field") |
| Add query param | .given().queryParam("key", "value") |
| Add path param | .given().pathParam("id", 2).get("/users/{id}") |
| Add header | .given().header("Authorization", "Bearer " + token) |
| Log all | .given().log().all() / .then().log().all() |
| Log on failure | .log().ifValidationFails() |
| Bearer auth | .given().header("Authorization", "Bearer " + token) |
| Basic auth | .given().auth().basic("user", "pass") |
| Reusable spec | given().spec(requestSpec) |
| JSON schema validation | .body(matchesJsonSchemaInClasspath("schema.json")) |
| Response time | .then().time(lessThan(2000L)) |
| Extract response | .then().extract().response() |
| JSON path | response.jsonPath().getString("data.name") |
10. What to Learn Next
Mastering REST Assured makes you a strong API automation engineer. To reach the architect level, add these to your skillset:
- TestNG — parallel execution, test groups, data providers, and reporting integration are all foundational to REST Assured framework design → TestNG Automation Framework Guide
- Cucumber BDD — combining REST Assured with Cucumber lets you write API tests in plain English that business stakeholders can review → Cucumber Automation Framework Guide
- API Authentication — JWT, OAuth 2.0, and API key patterns appear in nearly every API test suite → Ultimate API Authentication Guide
- Playwright — if your role includes UI automation alongside API testing → Playwright Interview Questions Guide
Final Conclusion
If you can answer the questions in this guide with code — not just definitions — you are operating at a strong SDET standard. The engineers who get rejected are not those who lack knowledge. They are those who cannot translate knowledge into clear, confident explanations with real examples.
Study this guide, write the code yourself in an IDE, and run it against the public reqres.in API until your fingers type the patterns without thinking.
The offer is on the other side of that preparation.
Published by Ajit Marathe · QaTribe — QA, Automation & Testing Made Simple
REST Assured Interview Questions: 50+ Real Questions (2026) | QaTribe
🔥 Continue Your Learning Journey:
Want to go beyond Playwright with Typescript setup and crack interviews faster? Check these hand-picked guides:
👉 🚀 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