Rest Assured interview questions
Updated 2026-11-13 · 11 min read
Thirty Rest Assured interview questions with Java examples and practical API scenarios. Covers readable assertions, isolated data, safe logging and framework design.
A good API automation answer connects the request, the contract and the observable business result. These examples use local ShopLite routes rather than a public service whose data can change during an interview.
Requests and assertions
1. What is Rest Assured?
Rest Assured is a Java library for sending HTTP requests and asserting on their responses. It lets a tester express request setup and expected results close together. It does not decide which test classes run or start your application; use a test runner and arrange the environment separately.
2. What do given, when and then mean?
given() prepares the request, when() introduces the action and then() starts response validation. The names make the flow readable, but using them does not by itself mean the team practices BDD. A useful test still needs a specific expectation such as the requested product id.
3. How do you write a basic GET test?
This complete test class requests an existing ShopLite product. Static imports make the request DSL and Hamcrest matcher available.
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
public class ProductTest {
@Test
public void returnsRequestedProduct() {
given()
.baseUri("http://localhost:3001")
.pathParam("id", 3)
.when()
.get("/api/products/{id}")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("id", equalTo(3));
}
}
Do not copy a response into an expected value automatically: the expected id comes from the request and contract.
4. How do path and query parameters differ?
A path parameter identifies part of the route, such as product 3 in /api/products/{id}. A query parameter modifies the request, such as q=backpack on /api/products. Use pathParam and queryParam rather than concatenating unescaped values; an ampersand inside a search term must not become a second parameter accidentally.
5. How do you send a JSON body?
Set the content type and pass a string, map or serializable object to body. For ShopLite cart setup, the JSON fields are productId and qty, not a guessed quantity field. A content-type error and an invalid business value are different negative cases; vary one thing at a time so the failure is interpretable.
6. How do request content type and Accept differ?
contentType describes the body you send; accept tells the server which response types the client prefers. A JSON POST may need both, while a GET with no body often only needs Accept. Assert the returned content type before relying on JSON field extraction, especially when a proxy may return an HTML error page.
7. How do you validate headers and status?
Use statusCode for the expected code and header or contentType for relevant response metadata. For a 201 creation, check the new id and any promised location as well. Avoid asserting every incidental server header: infrastructure changes should not fail tests unless they break a contract or a security requirement.
8. How do you assert nested values and arrays?
Pass a response path and a Hamcrest matcher to body. ShopLite's product list has an items array, so items.id selects its ids in the traditional path engine. Check the expected ids or each matching item's properties; merely proving the array is nonempty does not prove the search filter worked.
9. Is Rest Assured JSONPath the same as Jayway JSONPath?
The traditional Rest Assured JsonPath API uses Groovy GPath expressions. A filter copied from another JSON tool may therefore have different syntax; newer engine choices also make version and configuration relevant. For example, inspect your actual list response before choosing between a top-level array path and items.id.
10. How do you extract data without skipping validation?
Validate first, then extract from the validated response. This fragment assumes the static imports from question 3 and can sit inside a test method.
int productId = given()
.baseUri("http://localhost:3001")
.when()
.get("/api/products/3")
.then()
.statusCode(200)
.body("id", equalTo(3))
.extract().path("id");
Check numeric types when assigning paths to Java variables; an integer id and a decimal price do not necessarily deserialize to the same wrapper type.
Reuse, authentication and mapping
11. What is a request specification?
A RequestSpecification holds reusable request settings such as the base URI, Accept header and filters. Use RequestSpecBuilder to build one and .spec(...) to apply it. Keep scenario-specific ids, bodies and identity out of a global specification so a request for user B does not accidentally inherit user A's token.
12. How do you build a reusable request specification?
This helper creates a specification per call instead of mutating a shared global base URI. Call given().spec(LocalApi.spec()) in the test, with the static given import shown earlier.
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
public final class LocalApi {
private LocalApi() {}
public static RequestSpecification spec() {
return new RequestSpecBuilder()
.setBaseUri("http://localhost:3001")
.setAccept(ContentType.JSON)
.build();
}
}
Environment configuration should supply the URI in a real framework. Reject an unexpected target before running destructive checks.
13. What is a response specification?
It packages common expectations through ResponseSpecBuilder, for example JSON content and a successful read status. Apply it only where those expectations hold. A spec that requires 200 everywhere will reject a correct 204 delete and can encourage people to weaken negative tests instead of separating their contracts.
14. How do Basic and bearer authentication work in the DSL?
Basic auth uses .auth().basic(user, password); preemptive Basic uses .auth().preemptive().basic(user, password). For a bearer access token, .auth().oauth2(token) supplies it, but does not perform an interactive login or refresh it automatically. Keep credentials outside source and test missing or wrong credentials separately from permission checks.
15. How do you chain login and a profile request?
Post to /api/auth/login, assert 200, extract token, then send it on /api/me. Assert the returned email matches the account that logged in, not just that it contains an @. Avoid a suite-wide mutable token when parallel tests represent different users; identity belongs to each test's context.
16. What is serialization, and what dependency does it need?
Serialization turns a Java object into a request representation such as JSON. Rest Assured can use supported object mappers, including Jackson or Gson, when compatible libraries are on the classpath. A POJO with the wrong property name can send syntactically valid JSON that violates the API; inspect a sanitised body when debugging mapping failures.
17. What is deserialization, and when is a POJO useful?
Deserialization maps a response into a Java type, for example .as(Product.class). A POJO gives readable typed access when many tests use the same response model. Keep a few raw-contract checks too: permissive mapping may ignore unexpected fields and hide accidental exposure of a password hash.
18. How do you handle lists and generic response types?
Use an appropriate generic type reference when the response itself is a generic list or wrapper; a raw List.class loses element type information. First confirm whether the payload is an array or an object containing items. A mapping error caused by the wrong top-level shape will not be fixed by adding more field assertions.
19. How do you validate money accurately?
Follow the API's units and types. ShopLite uses integer paise, so ₹149 is represented as 14900; compare those integers directly for subtotal calculations. For decimal-money APIs, use a deliberate decimal strategy such as BigDecimal configuration rather than exact equality between binary floating-point approximations.
20. How do you validate a JSON schema?
Add the compatible json-schema-validator module, store a schema on the test classpath, and use matchesJsonSchemaInClasspath. This example requires src/test/resources/schemas/product.json containing a product schema.
import static io.restassured.RestAssured.given;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import org.testng.annotations.Test;
public class ProductSchemaTest {
@Test
public void productMatchesSchema() {
given().baseUri("http://localhost:3001")
.when().get("/api/products/3")
.then().statusCode(200)
.body(matchesJsonSchemaInClasspath("schemas/product.json"));
}
}
A minimal product.json checks two required fields without forbidding the product's other fields:
{
"type": "object",
"required": ["id", "price"],
"properties": {
"id": { "type": "integer" },
"price": { "type": "integer", "minimum": 0 }
}
}
Check the requested product id separately. Pick a schema draft supported by the actual validator dependency.
Evidence and framework design
21. What is a filter?
A filter can inspect or alter a request and response around execution. It can add a correlation id, collect timing or implement sanitised logging in one place. Avoid filters that silently retry every POST: a timeout does not tell you whether the server committed a payment or order.
22. How do you log only when validation fails?
Rest Assured offers failure-triggered logging such as .log().ifValidationFails() on request and response validation paths. This reduces noise compared with logging every successful body. Configure redaction as well: failure-only logs can still expose bearer tokens, cookies and personal data, and response bodies need their own treatment.
23. Why is relaxedHTTPSValidation not a general CI fix?
It relaxes certificate verification, so it can hide a broken trust chain or a request reaching the wrong host. For an intentionally self-signed local service, document the exception or configure a test truststore. For staging failures, inspect certificate expiry, hostname and trusted issuers instead of copying the bypass into every request.
24. How do you test multipart upload?
Use multiPart with the field name expected by the API and a harmless fixture file. Assert the stored metadata and retrieval behaviour as well as the upload status. Test wrong type, size boundaries and missing permissions separately; ShopLite does not expose an upload route, so that exercise needs a different authorised test endpoint.
25. How do you test eventual consistency?
Poll a read or job-status endpoint until the promised state appears or a bounded deadline expires. Preserve the final response when the deadline fails and use an interval that respects the environment. Do not repeatedly POST the same order while waiting for it to appear; that changes the system rather than observing it.
26. How should tests isolate data for parallel execution?
Give each test its own account or resource ids and keep mutable request configuration local. Avoid resetting the whole shared application while another thread is reading its cart. For ShopLite, separate instances are an option for reset-heavy suites; for a shared environment, create and clean up only records owned by that test.
27. How would you structure an API framework?
Separate configuration, HTTP clients, request builders, response models, fixtures and tests. A client should make the call and return enough detail for the test to assert both positive and negative cases. A helper that always asserts 200 prevents tests from checking expected 401s or 409s and hides the contract in the wrong layer.
Likely follow-up: Should every endpoint get a complicated abstraction? No. Extract repeated intent and setup after real duplication appears; a one-line wrapper around every DSL call may make tests harder to read.
28. What should a failure report contain?
Include method, sanitised URL, expected outcome, actual status, useful body fields, revision and any correlation id. For a wrong cart total, record quantities and amounts in their units so another tester can recompute it. Do not attach complete authentication responses just because the reporter accepts arbitrary text.
29. A test passes in Postman but fails in Java. What do you compare?
Compare the effective URL, query encoding, auth header, cookies, body, content type and environment. Postman might have retained cookies or substituted a different variable. Then compare assertion types: a Java matcher expecting an integer can fail against a decimal even when the displayed digits look the same.
30. How do you decide which API checks belong in CI?
Run fast, deterministic contract and business-rule checks on pull requests against an isolated target. Keep destructive, long-running or external-provider checks in a deliberate stage with safe test accounts and clear failure ownership. A green mocked suite proves behaviour against its fixtures; retain separate evidence for the real integration.
Practise it
Start ShopLite, write the product test above, then add login and profile checks. Extend the suite with two independent users and prove one cannot read the other's order. Review API testing questions for the business cases before adding more framework classes.
Quick answers
Is Rest Assured a test runner?
No. It sends requests and validates responses. A runner such as TestNG or JUnit discovers tests and reports their outcomes.
Does schema validation replace value assertions?
No. A response can have the correct types but contain the wrong user's data or an incorrect total.
Is Rest Assured JSONPath identical to every JSONPath tool?
No. Its traditional JsonPath uses Groovy GPath expressions. Check the configured engine and version before reusing expressions from another tool.
Sources
Want a project you can show in interviews?
The portfolio project kit walks you through testing a deliberately buggy app with Selenium or Playwright and API tests, then explaining it. The app itself is free.
