15 REST Assured API Testing Interview Questions and Answers
Prepare for your next interview with our comprehensive guide on REST Assured API testing, featuring expert insights and practical examples.
Prepare for your next interview with our comprehensive guide on REST Assured API testing, featuring expert insights and practical examples.
REST Assured is a powerful library in the Java ecosystem used for testing RESTful web services. It simplifies the process of validating and verifying APIs by providing a domain-specific language (DSL) for writing tests. This tool is particularly valuable for ensuring the reliability and performance of APIs, which are critical components in modern software architectures.
This article offers a curated selection of interview questions and answers focused on REST Assured API testing. By familiarizing yourself with 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 that simplifies testing RESTful web services by making HTTP requests and asserting responses. It supports various HTTP methods and payload types, including JSON and XML. Its fluent API allows for readable and maintainable tests, facilitating integration into the development process.
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"; // Example of a GET request given(). when(). get("/posts/1"). then(). assertThat(). statusCode(200). body("userId", equalTo(1)). body("id", equalTo(1)). body("title", notNullValue()); } }
To send a POST request with a JSON payload, set up the request with the appropriate headers and body content using REST Assured’s fluent API.
Example:
import io.restassured.RestAssured; import io.restassured.response.Response; public class RestAssuredExample { public static void main(String[] args) { String jsonPayload = "{ \"name\": \"John\", \"age\": 30 }"; Response response = RestAssured.given() .header("Content-Type", "application/json") .body(jsonPayload) .post("https://api.example.com/users"); System.out.println("Response: " + response.getBody().asString()); } }
Common assertions in API testing include verifying status codes, response times, headers, body content, and schema validation.
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://api.example.com"; given(). header("Content-Type", "application/json"). when(). get("/endpoint"). then(). assertThat(). statusCode(200). and(). header("Content-Type", equalTo("application/json")). and(). body("data.id", equalTo(1)). and(). time(lessThan(2000L)); } }
To validate the structure of a JSON response, use JSON schema validation. This ensures the response adheres to the expected structure.
Example:
import io.restassured.RestAssured; import io.restassured.module.jsv.JsonSchemaValidator; import org.junit.Test; public class ApiTest { @Test public void validateJsonResponseStructure() { RestAssured.given() .when() .get("https://api.example.com/data") .then() .assertThat() .body(JsonSchemaValidator.matchesJsonSchemaInClasspath("schema.json")); } }
To handle multipart form data, use the multiPart
method to specify the file, its content type, and the form field name.
Example:
import io.restassured.RestAssured; import io.restassured.response.Response; import java.io.File; public class MultipartFormDataExample { public static void main(String[] args) { File file = new File("path/to/your/file.txt"); Response response = RestAssured.given() .multiPart("file", file, "text/plain") .formParam("param1", "value1") .formParam("param2", "value2") .post("http://example.com/upload"); System.out.println("Response: " + response.asString()); } }
To set custom headers, use the header
or headers
methods to pass additional information with the HTTP request.
Example:
import io.restassured.RestAssured; import io.restassured.response.Response; public class CustomHeaderExample { public static void main(String[] args) { Response response = RestAssured.given() .header("Custom-Header", "HeaderValue") .header("Another-Header", "AnotherValue") .get("https://api.example.com/endpoint"); System.out.println(response.getStatusCode()); } }
Data-driven testing involves using external sources like Excel or CSV files to drive test cases, allowing for the separation of test logic and data. This can be implemented using a testing framework like TestNG.
Example:
import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static io.restassured.RestAssured.*; import static org.hamcrest.Matchers.*; public class DataDrivenTest { @DataProvider(name = "userData") public Object[][] createUserData() { return new Object[][] { { "user1", "password1" }, { "user2", "password2" }, { "user3", "password3" } }; } @Test(dataProvider = "userData") public void testUserLogin(String username, String password) { given() .auth().preemptive().basic(username, password) .when() .get("https://api.example.com/login") .then() .statusCode(200) .body("authenticated", equalTo(true)); } }
Filters allow you to intercept and modify requests and responses, adding common functionality like logging or authentication across multiple tests.
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) { requestSpec.header("Custom-Header", "HeaderValue"); System.out.println("Request: " + requestSpec.getMethod() + " " + requestSpec.getURI()); Response response = ctx.next(requestSpec, responseSpec); System.out.println("Response: " + response.getStatusCode()); return response; } }
To use the custom filter:
import static io.restassured.RestAssured.given; public class APITest { public void testWithCustomFilter() { given() .filter(new CustomFilter()) .when() .get("https://api.example.com/data") .then() .statusCode(200); } }
To integrate REST Assured with Jenkins, set up Jenkins, install necessary plugins, create a Jenkins job, configure build steps, and set up post-build actions to publish test results.
To validate XML responses, use REST Assured’s XML validation features to parse and assert specific values or structures within the XML document.
Example:
import io.restassured.RestAssured; import io.restassured.path.xml.XmlPath; import static io.restassured.RestAssured.*; import static org.hamcrest.Matchers.*; public class XmlResponseValidation { public static void main(String[] args) { RestAssured.baseURI = "https://api.example.com"; given() .when() .get("/endpoint") .then() .statusCode(200) .body("response.element", equalTo("expectedValue")) .body("response.element.attribute", equalTo("expectedAttributeValue")); } }
Custom matchers allow you to define specific validation rules beyond the built-in matchers. Use the Hamcrest library to create custom matchers by extending the TypeSafeMatcher
class.
Example:
import org.hamcrest.Description; import org.hamcrest.TypeSafeMatcher; public class CustomStatusCodeMatcher extends TypeSafeMatcher<Integer> { private final int expectedStatusCode; public CustomStatusCodeMatcher(int expectedStatusCode) { this.expectedStatusCode = expectedStatusCode; } @Override protected boolean matchesSafely(Integer actualStatusCode) { return actualStatusCode == expectedStatusCode; } @Override public void describeTo(Description description) { description.appendText("expected status code to be ").appendValue(expectedStatusCode); } @Override protected void describeMismatchSafely(Integer item, Description mismatchDescription) { mismatchDescription.appendText("was ").appendValue(item); } public static CustomStatusCodeMatcher hasStatusCode(int statusCode) { return new CustomStatusCodeMatcher(statusCode); } }
Use this custom matcher in your tests:
import static io.restassured.RestAssured.given; import static CustomStatusCodeMatcher.hasStatusCode; given() .when() .get("/api/resource") .then() .assertThat() .statusCode(hasStatusCode(200));
Schema validation ensures that the JSON or XML response adheres to a predefined structure. REST Assured supports JSON Schema validation.
Example:
import static io.restassured.RestAssured.*; import static io.restassured.module.jsv.JsonSchemaValidator.*; public class SchemaValidationTest { public static void main(String[] args) { given(). get("https://api.example.com/data"). then(). assertThat(). body(matchesJsonSchemaInClasspath("schema.json")); } }
Manage environment-specific configurations using properties files or environment variables to store details like base URLs and authentication tokens. Load the appropriate file based on the environment.
Example:
import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; public class ConfigManager { private static Properties properties = new Properties(); public static void loadProperties(String environment) { try { FileInputStream fileInputStream = new FileInputStream(environment + ".properties"); properties.load(fileInputStream); } catch (IOException e) { e.printStackTrace(); } } public static String getProperty(String key) { return properties.getProperty(key); } }
In your test setup:
public class BaseTest { @BeforeClass public void setup() { String environment = System.getProperty("env", "dev"); ConfigManager.loadProperties(environment); RestAssured.baseURI = ConfigManager.getProperty("baseURI"); } }
For maintainable tests, use descriptive names, organize tests logically, reuse code with helper methods, parameterize tests, use assertions effectively, handle test data properly, clean up after tests, and document tests.
REST Assured can be integrated with JUnit and TestNG to create comprehensive test suites.
Example with JUnit:
import io.restassured.RestAssured; import org.junit.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("/endpoint"). then(). statusCode(200). body("key", equalTo("value")); } }
Example with 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("/endpoint"). then(). statusCode(200). body("key", equalTo("value")); } }