15 REST Assured API Automation Interview Questions and Answers
Prepare for your next interview with this guide on REST Assured API automation, featuring common questions and expert insights.
Prepare for your next interview with this guide on REST Assured API automation, featuring common questions and expert insights.
REST Assured is a powerful tool for automating RESTful web services testing. It simplifies the process of validating and verifying APIs by providing a domain-specific language (DSL) for writing tests in Java. This makes it an essential skill for quality assurance engineers and developers who aim to ensure the reliability and performance of web services.
This article offers a curated selection of interview questions and answers focused on REST Assured API automation. By reviewing these questions, you will gain a deeper understanding of key concepts and best practices, enhancing your ability to demonstrate your expertise in API testing during interviews.
REST Assured is a Java library designed for testing RESTful web services. It provides a domain-specific language (DSL) for writing tests, simplifying the process of sending HTTP requests and validating responses. This is essential for ensuring the reliability and correctness of APIs.
Example:
import io.restassured.RestAssured; import io.restassured.response.Response; import static io.restassured.RestAssured.*; import static org.hamcrest.Matchers.*; public class ApiTest { public static void main(String[] args) { RestAssured.baseURI = "https://jsonplaceholder.typicode.com"; given(). when(). get("/posts/1"). then(). assertThat(). statusCode(200). body("userId", equalTo(1)). body("id", equalTo(1)). body("title", notNullValue()); } }
In this example, REST Assured sends a GET request to a sample API and validates the response, checking that the status code is 200 and specific fields in the response body have the expected values.
To send a GET request using REST Assured, follow these steps:
Example:
import io.restassured.RestAssured; import io.restassured.response.Response; public class GetRequestExample { public static void main(String[] args) { RestAssured.baseURI = "https://jsonplaceholder.typicode.com"; Response response = RestAssured .given() .when() .get("/posts/1") .then() .statusCode(200) .extract() .response(); System.out.println(response.asString()); } }
In this example, a GET request is sent to the endpoint “/posts/1”, and the response is validated to ensure the status code is 200.
Validating the status code of a response is a fundamental step to ensure that the API behaves as expected. REST Assured provides a straightforward way to validate the status code using its built-in methods.
Example:
import io.restassured.RestAssured; import io.restassured.response.Response; public class StatusCodeValidation { public static void main(String[] args) { Response response = RestAssured.get("https://api.example.com/resource"); int statusCode = response.getStatusCode(); // Validate the status code if (statusCode == 200) { System.out.println("Status code is 200: OK"); } else { System.out.println("Unexpected status code: " + statusCode); } } }
In REST Assured, query parameters can be added to a request using the queryParam
method, which allows you to specify key-value pairs that will be appended to the URL.
Example:
import io.restassured.RestAssured; import io.restassured.response.Response; public class QueryParamExample { public static void main(String[] args) { Response response = RestAssured.given() .queryParam("param1", "value1") .queryParam("param2", "value2") .when() .get("https://api.example.com/resource"); System.out.println(response.getBody().asString()); } }
In this example, the queryParam
method is used to add two query parameters to the request.
To send a POST request with a JSON body using REST Assured, set up the request with the appropriate headers and body content.
Example:
import io.restassured.RestAssured; import io.restassured.response.Response; import static io.restassured.RestAssured.given; public class PostRequestExample { public static void main(String[] args) { RestAssured.baseURI = "https://api.example.com"; String jsonBody = "{ \"name\": \"John\", \"age\": 30 }"; Response response = given() .header("Content-Type", "application/json") .body(jsonBody) .when() .post("/users") .then() .statusCode(201) .extract() .response(); System.out.println("Response: " + response.asString()); } }
To extract values from a JSON response, use the JsonPath
class, which allows you to parse and query JSON data.
Example:
import io.restassured.RestAssured; import io.restassured.response.Response; import io.restassured.path.json.JsonPath; public class ExtractValues { public static void main(String[] args) { Response response = RestAssured.get("https://api.example.com/data"); JsonPath jsonPath = response.jsonPath(); String value = jsonPath.getString("key"); System.out.println("Extracted Value: " + value); } }
In this example, the jsonPath
method is used to create a JsonPath
object, which allows you to extract values using JSON path expressions.
Path parameters are used in RESTful APIs to identify specific resources. In REST Assured, you can handle path parameters using the pathParam
method.
Example:
import io.restassured.RestAssured; import io.restassured.response.Response; public class PathParameterExample { public static void main(String[] args) { Response response = RestAssured.given() .pathParam("userId", 1) .when() .get("https://jsonplaceholder.typicode.com/users/{userId}"); System.out.println(response.getBody().asString()); } }
In this example, the pathParam
method is used to set the userId
path parameter.
Headers in REST Assured are used to pass additional information with an HTTP request or response. To set headers, use the header
or headers
methods.
Example:
import io.restassured.RestAssured; import io.restassured.response.Response; public class RestAssuredExample { public static void main(String[] args) { Response response = RestAssured.given() .header("Content-Type", "application/json") .header("Authorization", "Bearer your_token_here") .get("https://api.example.com/data"); System.out.println(response.getStatusCode()); } }
In this example, the header
method is used to set the “Content-Type” and “Authorization” headers.
Logging request and response details is essential for debugging and ensuring that the API calls are functioning as expected. REST Assured provides built-in methods to log various parts of the request and response.
Example:
import io.restassured.RestAssured; import io.restassured.response.Response; public class APILoggingExample { public static void main(String[] args) { Response response = RestAssured.given() .log().all() // Log all request details .when() .get("https://jsonplaceholder.typicode.com/posts/1") .then() .log().all() // Log all response details .extract().response(); } }
In this example, the log().all()
method is used to log all details of the request and response.
Filters in REST Assured allow you to apply common functionality to your requests and responses. They can be used for logging, adding headers, or modifying the request and response.
Example:
import io.restassured.filter.Filter; import io.restassured.filter.FilterContext; import io.restassured.response.Response; import io.restassured.specification.FilterableRequestSpecification; import io.restassured.specification.FilterableResponseSpecification; public class CustomFilter implements Filter { @Override public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) { // Add a custom header requestSpec.header("Custom-Header", "value"); // Log the request System.out.println("Request: " + requestSpec.getMethod() + " " + requestSpec.getURI()); // Proceed with the request Response response = ctx.next(requestSpec, responseSpec); // Log the response System.out.println("Response: " + response.getStatusCode()); return response; } }
To use the custom filter in your tests:
import static io.restassured.RestAssured.given; public class APITest { public void testAPI() { given() .filter(new CustomFilter()) .when() .get("https://api.example.com/data") .then() .statusCode(200); } }
Integrating REST Assured API tests with a CI/CD pipeline involves several steps to ensure that your tests are automatically executed as part of your continuous integration and deployment processes:
REST Assured can be extended with custom matchers or assertions to tailor validation to specific requirements. Custom matchers can be created using the Hamcrest library, which REST Assured integrates with.
Example:
import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; public class CustomMatchers { public static TypeSafeMatcher<String> containsSubstring(final String substring) { return new TypeSafeMatcher<String>() { @Override public void describeTo(Description description) { description.appendText("a string containing ").appendValue(substring); } @Override protected boolean matchesSafely(String item) { return item.contains(substring); } }; } public static void main(String[] args) { String response = "This is a sample response"; assertThat(response, containsSubstring("sample")); } }
In this example, a custom matcher containsSubstring
is created to check if a string contains a specific substring.
Error handling in REST Assured tests is important for ensuring that your API behaves as expected under various conditions. Here are some strategies to consider:
1. HTTP Status Code Validation: Always validate the HTTP status codes returned by the API.
2. Response Body Validation: Validate the response body to ensure that it contains the expected data.
3. Exception Handling: Use try-catch blocks to handle exceptions that may occur during the execution of the tests.
4. Logging: Implement logging to capture detailed information about the requests and responses.
Example:
import io.restassured.RestAssured; import io.restassured.response.Response; import static io.restassured.RestAssured.*; import static org.hamcrest.Matchers.*; public class ApiTest { public static void main(String[] args) { try { Response response = given() .baseUri("https://api.example.com") .when() .get("/endpoint") .then() .statusCode(200) .body("key", equalTo("value")) .extract() .response(); // Additional validation if (response.jsonPath().getString("anotherKey") == null) { throw new AssertionError("anotherKey is missing in the response"); } } catch (Exception e) { System.err.println("Error occurred: " + e.getMessage()); } } }
To integrate REST Assured with TestNG or JUnit, add the necessary dependencies to your project. If you are using Maven, add the following dependencies to your pom.xml
file:
For TestNG:
<dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>4.3.3</version> <scope>test</scope> </dependency> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.3.0</version> <scope>test</scope> </dependency>
For JUnit:
<dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>4.3.3</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.1</version> <scope>test</scope> </dependency>
Next, write your test cases using REST Assured with TestNG or JUnit. Here is an example of a simple test case using TestNG:
import io.restassured.RestAssured; import io.restassured.response.Response; import org.testng.Assert; import org.testng.annotations.Test; public class ApiTest { @Test public void testGetRequest() { Response response = RestAssured.get("https://jsonplaceholder.typicode.com/posts/1"); Assert.assertEquals(response.getStatusCode(), 200); Assert.assertEquals(response.jsonPath().getString("id"), "1"); } }
And here is an example using JUnit:
import io.restassured.RestAssured; import io.restassured.response.Response; import org.junit.Assert; import org.junit.Test; public class ApiTest { @Test public void testGetRequest() { Response response = RestAssured.get("https://jsonplaceholder.typicode.com/posts/1"); Assert.assertEquals(200, response.getStatusCode()); Assert.assertEquals("1", response.jsonPath().getString("id")); } }
When writing REST Assured tests, follow these best practices to ensure your tests are maintainable, readable, and effective: