Are you preparing for a REST Assured interview? API testing with REST Assured is one of the most widely used methods for testing RESTful web services. Built on Java, REST Assured provides a powerful, simple, and flexible framework for validating APIs. It allows testers and developers to write clean, maintainable, and reusable tests for API endpoints without needing extensive boilerplate code. This list of the top 30 REST Assured Interview Questions and Answers will help you prepare for interviews in 2025.
These questions cover basic, intermediate, and advanced concepts, including handling requests, responses, headers, cookies, authentication, file uploads, JSON schema validation, and much more.
Top 30+ REST Assured Interview Questions and Answers
- What is REST Assured?
- How do you add REST Assured to your project?
- Explain the main components of a REST Assured test script.
- What are the various HTTP methods supported by REST Assured?
- How do you send a GET request using REST Assured?
- Explain REST Assured method chaining.
- Explain the difference between ‘given()’, ‘when()’, and ‘then()’ in REST Assured.
- What is the request specification, and how is it initiated?
- How do you handle authentication in REST Assured?
- What is the role of the ‘baseURI’ and ‘basePath’ methods in REST Assured?
- How do you validate responses in REST Assured?
- How do you extract data from a response in REST Assured?
- How do you validate response status codes and headers in REST Assured?
- How can you send a POST request with a JSON body using REST Assured?
- How do you handle path parameters and query parameters in REST Assured?
- How can you perform data-driven testing with REST Assured?
- How do you handle file uploads and downloads using REST Assured?
- How do you perform JSON schema validation with REST Assured?
- How can you handle SSL certificate validation in REST Assured?
- How do you integrate REST Assured with testing frameworks like JUnit or TestNG?
- How do you handle cookies in REST Assured?
- How can you validate response time using REST Assured?
- How do you handle different content types in REST Assured?
- How do you handle dynamic response content in REST Assured?
- How do you handle request and response logging in REST Assured?
- How can you validate XML responses in REST Assured?
- How do you handle multipart form data in REST Assured?
- How do you handle form URL encoded data in REST Assured?
- How can you handle redirects in REST Assured?
- How do you handle timeouts in REST Assured?
- How can you validate response headers in REST Assured?
1. What is REST Assured?
REST Assured is an open-source Java library that simplifies testing of RESTful APIs. It provides a domain-specific language (DSL) for writing powerful, maintainable tests for REST services. With REST Assured, developers can easily validate and verify the responses of REST APIs without extensive coding.
2. How do you add REST Assured to your project?
To include REST Assured in a Maven project, add the following dependency to your pom.xml
file:
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>4.4.0</version>
<scope>test</scope>
</dependency>
For Gradle projects, add the following to your build.gradle
file:
testImplementation 'io.rest-assured:rest-assured:4.4.0'
Ensure you replace 4.4.0
with the latest version available.
3. Explain the main components of a REST Assured test script.
A REST Assured test script typically consists of:
- Base URI: The root address of the API.
- Request Specification: Details like headers, parameters, and authentication.
- HTTP Method: The type of request (e.g., GET, POST).
- Response Validation: Assertions to verify the response status code, headers, and body content.
4. What are the various HTTP methods supported by REST Assured?
REST Assured supports all standard HTTP methods used in RESTful services, including:
- GET: Retrieve data from a server.
- POST: Send data to the server to create a resource.
- PUT: Update an existing resource or create a new one if it doesn’t exist.
- DELETE: Remove a resource from the server.
- PATCH: Apply partial modifications to a resource.
- OPTIONS: Describe the communication options for the target resource.
- HEAD: Similar to GET but retrieves only the headers.
5. How do you send a GET request using REST Assured?
To send a GET request:
Response response = given()
.baseUri("https://api.example.com")
.when()
.get("/resource");
6. Explain REST Assured method chaining.
Method chaining in REST Assured allows for a fluent API, enabling multiple methods to be called in a single statement. Each method returns an object, allowing subsequent methods to be chained together, enhancing readability and maintainability.
7. Explain the difference between ‘given()’, ‘when()’, and ‘then()’ in REST Assured.
given()
: Specifies the request’s preconditions, such as headers, parameters, and body.when()
: Defines the HTTP method and endpoint to be called.then()
: Sets the expected outcomes, including assertions on status codes and response data.
This structure aligns with Behavior-Driven Development (BDD) principles.
8. What is the request specification, and how is it initiated?
A request specification in REST Assured defines the common settings for requests, such as base URI, headers, and authentication. It’s initiated using the given()
method:
RequestSpecification reqSpec = given()
.baseUri("https://api.example.com")
.header("Content-Type", "application/json");
9. How do you handle authentication in REST Assured?
REST Assured supports various authentication mechanisms:
Basic Authentication:
given()
.auth()
.basic("username", "password");
OAuth 2.0:
given()
.auth()
.oauth2("accessToken");
Preemptive Basic Authentication:
given()
.auth()
.preemptive()
.basic("username", "password");
10. What is the role of the ‘baseURI’ and ‘basePath’ methods in REST Assured?
baseURI
: Sets the base URL for the API, reducing redundancy in test scripts.
RestAssured.baseURI = "https://api.example.com";
basePath
: Defines the base path for the API endpoints
RestAssured.basePath = "/v1";
Combining these simplifies request definitions.
11. How do you validate responses in REST Assured?
Responses can be validated using assertions:
given()
.when()
.get("/resource")
.then()
.statusCode(200)
.body("key", equalTo("value"));
This checks that the status code is 200 and the response body contains the specified key-value pair.
12. How do you extract data from a response in REST Assured?
To extract data from a response in REST Assured, you can utilize methods like jsonPath()
for JSON responses and xmlPath()
for XML responses. These methods allow you to navigate through the response structure and retrieve specific values.
Extracting Data from JSON Responses:
1. Using jsonPath()
Method:The jsonPath()
method enables parsing of JSON responses to extract specific data. Here’s how to use it:
Response response = given()
.when()
.get("/resource");
// Extracting a single value
String value = response.jsonPath().getString("key");
// Extracting a nested value
String nestedValue = response.jsonPath().getString("parent.child");
// Extracting a list of values
List<String> values = response.jsonPath().getList("items.name");
In this example:
getString("key")
retrieves the value associated withkey
.getString("parent.child")
accesses a nested value.getList("items.name")
fetches a list ofname
values from an array ofitems
.
2. Using extract().path()
Method:Alternatively, you can use the extract().path()
method to obtain data:
String value = given()
.when()
.get("/resource")
.then()
.extract()
.path("key");
This approach combines request execution and data extraction in a fluent manner.
Extracting Data from XML Responses:
For XML responses, REST Assured provides the xmlPath()
method:
Response response = given()
.when()
.get("/resource");
String value = response.xmlPath().getString("path.to.element");
Here, getString("path.to.element")
retrieves the text content of the specified XML element.
Example:
Suppose you have the following JSON response:
{
"id": 1,
"name": "John Doe",
"contacts": [
{"type": "email", "value": "[email protected]"},
{"type": "phone", "value": "123-456-7890"}
]
}
To extract the email address:
String email = given()
.when()
.get("/user/1")
.then()
.extract()
.path("contacts.find { it.type == 'email' }.value");
In this example, contacts.find { it.type == 'email' }.value
uses a Groovy closure to find the contact with type ’email’ and retrieves its value.
By leveraging these methods, you can effectively extract and utilize data from API responses in your REST Assured tests.
13. How do you validate response status codes and headers in REST Assured?
In REST Assured, you can validate response status codes and headers using the then()
method followed by appropriate assertions.
Validating Status Codes:
given()
.when()
.get("/resource")
.then()
.statusCode(200); // Asserts that the status code is 200 (OK)
Validating Headers:
given()
.when()
.get("/resource")
.then()
.header("Content-Type", "application/json"); // Asserts that the 'Content-Type' header is 'application/json'
You can chain multiple assertions to validate various aspects of the response.
14. How can you send a POST request with a JSON body using REST Assured?
To send a POST request with a JSON body in REST Assured, you need to set the Content-Type
header to application/json
and include the JSON payload in the body of the request.
String jsonBody = "{ \"key\": \"value\" }";
given()
.header("Content-Type", "application/json")
.body(jsonBody)
.when()
.post("/resource")
.then()
.statusCode(201); // Asserts that the status code is 201 (Created)
Alternatively, you can use the contentType
method for setting the Content-Type
header:
given()
.contentType(ContentType.JSON)
.body(jsonBody)
.when()
.post("/resource")
.then()
.statusCode(201);
15. How do you handle path parameters and query parameters in REST Assured?
REST Assured provides methods to handle both path parameters and query parameters.
Path Parameters:
Use the pathParam
method to specify path parameters.
given()
.pathParam("id", 123)
.when()
.get("/resource/{id}")
.then()
.statusCode(200);
In this example, {id}
in the URL is replaced with the value 123
.
Query Parameters:
Use the queryParam
method to add query parameters.
given()
.queryParam("type", "example")
.when()
.get("/resource")
.then()
.statusCode(200);
This sends a GET request to /resource?type=example
.
16. How can you perform data-driven testing with REST Assured?
Data-driven testing involves running the same test with multiple sets of data. In REST Assured, this can be achieved by integrating with testing frameworks like TestNG or JUnit, which support parameterized tests.
Using TestNG:
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class DataDrivenTest {
@DataProvider(name = "dataProvider")
public Object[][] dataProviderMethod() {
return new Object[][] { { "data1" }, { "data2" } };
}
@Test(dataProvider = "dataProvider")
public void testWithData(String data) {
given()
.queryParam("param", data)
.when()
.get("/resource")
.then()
.statusCode(200);
}
}
In this example, the test testWithData
runs twice with different data provided by the dataProviderMethod
.
17. How do you handle file uploads and downloads using REST Assured?
File Upload:
To upload a file, use the multiPart
method to attach the file to the request.
File file = new File("path/to/file.txt");
given()
.multiPart("file", file)
.when()
.post("/upload")
.then()
.statusCode(200);
Here, "file"
is the name of the form parameter expected by the server.
File Download:
To download a file, send a GET request and retrieve the response as a byte array.
byte[] fileData = given()
.when()
.get("/download/file.txt")
.then()
.statusCode(200)
.extract()
.asByteArray();
// Save the fileData to a file
You can then write the fileData
to a file using standard Java I/O operations.
18. How do you perform JSON schema validation with REST Assured?
REST Assured allows you to validate the structure of a JSON response against a predefined schema using the matchesJsonSchemaInClasspath
method.
- Create a JSON Schema File: Save the JSON schema as a
.json
file in your project’s classpath. - Validate the Response Against the Schema:
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
given()
.when()
.get("/resource")
.then()
.body(matchesJsonSchemaInClasspath("schema.json"));
This ensures that the response body adheres to the specified JSON schema.
19. How can you handle SSL certificate validation in REST Assured?
By default, REST Assured performs SSL certificate validation for HTTPS requests. To bypass SSL certificate validation (e.g., when testing against self-signed certificates), you can use the relaxedHTTPSValidation
method.
given()
.relaxedHTTPSValidation()
.when()
.get("https://self-signed.badssl.com/")
.then()
.statusCode(200);
This disables SSL certificate validation for the request.
20. How do you integrate REST Assured with testing frameworks like JUnit or TestNG?
Integrating REST Assured with testing frameworks like JUnit or TestNG enhances the efficiency and organization of API tests. Here’s how to achieve this integration:
1. Add Dependencies:
Include the necessary dependencies for REST Assured and your chosen testing framework in your project’s build configuration.
For Maven:
<dependencies>
<!-- REST Assured -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>4.4.0</version>
<scope>test</scope>
</dependency>
<!-- JUnit 5 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
<!-- TestNG -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.4.0</version>
<scope>test</scope>
</dependency>
</dependencies>
For Gradle:
dependencies {
// REST Assured
testImplementation 'io.rest-assured:rest-assured:4.4.0'
// JUnit 5
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0'
// TestNG
testImplementation 'org.testng:testng:7.4.0'
}
2. Write Test Cases:
Create test classes and methods using the annotations provided by JUnit or TestNG. Within these methods, utilize REST Assured to perform API requests and assertions.
Using JUnit 5:
import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class ApiTest {
@Test
public void testGetEndpoint() {
RestAssured.baseURI = "https://api.example.com";
given()
.when()
.get("/resource")
.then()
.statusCode(200)
.body("key", equalTo("value"));
}
}
Using TestNG:
import io.restassured.RestAssured;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class ApiTest {
@Test
public void testGetEndpoint() {
RestAssured.baseURI = "https://api.example.com";
given()
.when()
.get("/resource")
.then()
.statusCode(200)
.body("key", equalTo("value"));
}
}
3. Execute Tests:
Run your tests using the test runner associated with your chosen framework. For JUnit, use the JUnit test runner; for TestNG, use the TestNG test runner.
4. Generate Reports:
Both JUnit and TestNG support test report generation. Configure your build tool (e.g., Maven or Gradle) to generate these reports after test execution.
By integrating REST Assured with JUnit or TestNG, you can create structured, maintainable, and automated API tests that fit seamlessly into your development workflow.
21. How do you handle cookies in REST Assured?
REST Assured provides methods to extract and manage cookies from responses, which can be used in subsequent requests.
Extracting Cookies:
Response response = given()
.when()
.get("/resource");
// Extract a specific cookie
String cookieValue = response.getCookie("cookieName");
// Extract all cookies
Map<String, String> allCookies = response.getCookies();
Using Cookies in Requests:
given()
.cookie("cookieName", cookieValue)
.when()
.get("/anotherResource")
.then()
.statusCode(200);
This approach is useful for maintaining sessions or handling authentication mechanisms that rely on cookies.
22. How can you validate response time using REST Assured?
REST Assured allows you to assert the response time to ensure APIs meet performance requirements.
Validating Response Time:
given()
.when()
.get("/resource")
.then()
.time(lessThan(2000L)); // Asserts that the response time is less than 2000 milliseconds
Extracting Response Time:
long responseTime = given()
.when()
.get("/resource")
.time();
System.out.println("Response time: " + responseTime + " ms");
Monitoring response times helps in identifying performance bottlenecks in APIs.
23. How do you handle different content types in REST Assured?
REST Assured can handle various content types by setting the appropriate Content-Type
header in requests and validating it in responses.
Setting Content Type in Requests:
given()
.contentType(ContentType.JSON) // For JSON requests
.body(jsonBody)
.when()
.post("/resource");
For XML requests:
given()
.contentType(ContentType.XML)
.body(xmlBody)
.when()
.post("/resource");
Validating Content Type in Responses:
given()
.when()
.get("/resource")
.then()
.contentType(ContentType.JSON); // Asserts that the response is in JSON format
Properly handling content types ensures correct parsing and processing of API requests and responses.
24. How do you handle dynamic response content in REST Assured?
Handling dynamic response content in REST Assured involves extracting values from the response and using them in assertions or subsequent requests.
Extracting Values:
Use the extract()
method to retrieve dynamic values from the response.
Response response = given()
.when()
.get("/resource");
String dynamicValue = response.jsonPath().getString("dynamicField");
Using Extracted Values:
Incorporate the extracted values into assertions or subsequent API calls.
given()
.pathParam("id", dynamicValue)
.when()
.get("/resource/{id}")
.then()
.statusCode(200);
This approach allows you to handle responses where certain fields may change dynamically, ensuring your tests remain robust.
25. How do you handle request and response logging in REST Assured?
REST Assured provides options to log request and response details, aiding in debugging and test transparency.
Logging Requests:
given()
.log().all() // Logs all request details
.when()
.get("/resource");
Logging Responses:
given()
.when()
.get("/resource")
.then()
.log().all(); // Logs all response details
Conditional Logging:
Log only if a test fails.
given()
.when()
.get("/resource")
.then()
.log().ifError(); // Logs response details only if there's an error
Implementing logging enhances the visibility of request-response cycles, facilitating easier troubleshooting.
26. How can you validate XML responses in REST Assured?
REST Assured supports validation of XML responses using XmlPath
and various assertion methods.
Extracting Values:
Response response = given()
.when()
.get("/resource");
String value = response.xmlPath().getString("path.to.element");
Validating Values:
given()
.when()
.get("/resource")
.then()
.body("path.to.element", equalTo("expectedValue"));
Using XPath Expressions:
given()
.when()
.get("/resource")
.then()
.body(hasXPath("/root/element"));
These methods allow for comprehensive validation of XML responses, ensuring the API returns the expected data structures.
27. How do you handle multipart form data in REST Assured?
REST Assured facilitates the testing of APIs that handle file uploads by supporting multipart form data. This is particularly useful when you need to upload files or submit forms that include files.
Uploading a File:
To upload a file using REST Assured, utilize the multiPart()
method to attach the file to your request.
File file = new File("path/to/file.txt");
given()
.multiPart("file", file)
.when()
.post("/upload")
.then()
.statusCode(200);
In this example:
"file"
is the name of the form parameter expected by the server.file
is theFile
object representing the file to be uploaded.
Uploading a File with Additional Form Data:
If you need to send additional form data along with the file, you can chain multiple multiPart()
methods or use the formParam()
method.
given()
.multiPart("file", file)
.multiPart("description", "Sample file upload")
.when()
.post("/upload")
.then()
.statusCode(200);
Here, an additional form field named "description"
with the value "Sample file upload"
is included in the request.
Specifying MIME Type:
You can also specify the MIME type of the file being uploaded.
given()
.multiPart("file", file, "text/plain")
.when()
.post("/upload")
.then()
.statusCode(200);
In this case, "text/plain"
is specified as the MIME type of the file.
By leveraging REST Assured’s support for multipart form data, you can effectively test file upload functionalities of your APIs.
28. How do you handle form URL encoded data in REST Assured?
REST Assured provides mechanisms to send form URL encoded data, which is commonly used in form submissions.
Sending Form URL Encoded Data:
Use the formParam()
method to add form parameters to your request.
given()
.contentType(ContentType.URLENC)
.formParam("username", "testuser")
.formParam("password", "testpass")
.when()
.post("/login")
.then()
.statusCode(200);
In this example:
contentType(ContentType.URLENC)
sets theContent-Type
header toapplication/x-www-form-urlencoded
.formParam()
methods add form parameters to the request body.
Sending Multiple Form Parameters:
You can send multiple form parameters by chaining formParam()
methods.
given()
.contentType(ContentType.URLENC)
.formParam("param1", "value1")
.formParam("param2", "value2")
.when()
.post("/submit")
.then()
.statusCode(200);
This approach is useful for testing APIs that process form submissions.
29. How can you handle redirects in REST Assured?
REST Assured automatically follows redirects by default. However, you can configure this behavior as needed.
Disabling Redirects:
To prevent REST Assured from following redirects, use the redirects().follow(false)
method.
given()
.redirects().follow(false)
.when()
.get("/redirect")
.then()
.statusCode(302); // Asserts that the response status is 302 Found
In this example, REST Assured will not follow the redirect, allowing you to assert the initial redirect response.
Configuring Maximum Redirects:
You can also set the maximum number of redirects to follow.
given()
.redirects().max(3)
.when()
.get("/redirect")
.then()
.statusCode(200);
This configuration ensures that REST Assured follows up to three redirects before stopping.
By managing redirect behavior, you can test how your application handles HTTP redirects and ensure it behaves as expected.
30. How do you handle timeouts in REST Assured?
REST Assured allows you to configure timeouts to ensure that your tests fail gracefully when a request takes too long.
Setting Connection and Socket Timeouts:
Use the config()
method along with HttpClientConfig
to set timeouts.
import static io.restassured.config.HttpClientConfig.httpClientConfig;
import static io.restassured.config.RestAssuredConfig.newConfig;
given()
.config(newConfig().httpClient(httpClientConfig()
.setParam("http.connection.timeout", 5000) // 5 seconds
.setParam("http.socket.timeout", 5000))) // 5 seconds
.when()
.get("/resource")
.then()
.statusCode(200);
In this example:
http.connection.timeout
sets the connection timeout.http.socket.timeout
sets the socket timeout.
By configuring timeouts, you can ensure that your tests do not hang indefinitely and handle slow responses appropriately.
31. How can you validate response headers in REST Assured?
Validating response headers in REST Assured ensures that the API returns the expected metadata, such as content type, server details, and caching policies.
Validating a Specific Header:
To assert the value of a specific header, use the header()
method in the response validation chain:
given()
.when()
.get("/resource")
.then()
.header("Content-Type", equalTo("application/json; charset=utf-8"));
This checks that the Content-Type
header is exactly application/json; charset=utf-8
.
Validating Multiple Headers:
To validate multiple headers simultaneously, use the headers()
method:
given()
.when()
.get("/resource")
.then()
.headers(
"Content-Type", equalTo("application/json; charset=utf-8"),
"Server", equalTo("nginx/1.17.10 (Ubuntu)")
);
This asserts that the Content-Type
and Server
headers have the specified values.
Validating Header Presence:
To verify that a header is present, regardless of its value, use the notNullValue()
matcher:
given()
.when()
.get("/resource")
.then()
.header("ETag", notNullValue());
This ensures that the ETag
header is present in the response.
Extracting and Validating Headers:
If you need to perform more complex validations or reuse header values, extract headers using the Response
object:
Response response = given()
.when()
.get("/resource");
String contentType = response.getHeader("Content-Type");
assertThat(contentType, equalTo("application/json; charset=utf-8"));
This approach allows for flexible validation and utilization of header values in your tests.
By validating response headers, you ensure that the API adheres to expected standards and behaviors, which is crucial for client applications relying on these headers for processing responses.
Learn More: Carrer Guidance | Hiring Now!
Top Android Developer Interview Q&A for 5+ Years Experience
Ansible Interview Questions and Answers
Django Interview Questions and Answers