10 REST Assured API Interview Questions and Answers
Prepare for your next interview with this guide on REST Assured API, featuring common questions and answers to enhance your API testing skills.
Prepare for your next interview with this guide on REST Assured API, featuring common questions and answers to enhance your API testing skills.
REST Assured is a powerful library in the Java ecosystem used for testing and validating RESTful web services. It simplifies the process of making HTTP requests and assertions, making it an essential tool for developers and testers working with APIs. With its intuitive syntax and extensive capabilities, REST Assured allows for efficient and effective API testing, ensuring that web services function as expected.
This article provides a curated selection of interview questions and answers focused on REST Assured. By familiarizing yourself with these questions, you will gain a deeper understanding of REST Assured’s features and best practices, enhancing your ability to demonstrate your expertise in API testing during interviews.
REST Assured is a Java library for testing RESTful web services. It simplifies writing tests for APIs, supporting various HTTP methods like GET, POST, PUT, and DELETE. REST Assured integrates with Java-based testing frameworks like JUnit and TestNG, allowing API tests to be part of standard test suites.
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()); } }
To validate a response’s status code in REST Assured, use the then()
method followed by statusCode()
. This asserts that the response status code matches the expected value.
Example:
import static io.restassured.RestAssured.*; import static org.hamcrest.Matchers.*; public class StatusCodeValidation { public static void main(String[] args) { given(). when(). get("https://api.example.com/resource"). then(). statusCode(200); } }
To send a POST request with a JSON body in REST Assured:
1. Set the base URI.
2. Specify the content type as JSON.
3. Create the JSON body.
4. Send the POST request.
Example:
import io.restassured.RestAssured; import io.restassured.response.Response; import static io.restassured.RestAssured.given; public class RestAssuredExample { 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.asString()); } }
To extract values from a JSON response, use the getBody()
method and parse it with the JsonPath
class.
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"); int id = jsonPath.getInt("id"); System.out.println("Value: " + value); System.out.println("ID: " + id); } }
Path parameters in RESTful APIs identify specific resources by embedding values within the URL. In REST Assured, use placeholders in the URL and provide actual values when making the request.
Example:
import io.restassured.RestAssured; import io.restassured.response.Response; public class PathParameterExample { public static void main(String[] args) { String baseUrl = "https://api.example.com/users/{userId}/posts/{postId}"; Response response = RestAssured .given() .pathParam("userId", 1) .pathParam("postId", 10) .when() .get(baseUrl); System.out.println(response.getBody().asString()); } }
To log request and response details in REST Assured, use the built-in logging methods. Logging can be configured at different levels.
Example:
import io.restassured.RestAssured; import io.restassured.response.Response; public class RestAssuredLoggingExample { public static void main(String[] args) { RestAssured.baseURI = "https://jsonplaceholder.typicode.com"; Response response = RestAssured.given() .log().all() // Log all request details .when() .get("/posts/1") .then() .log().all() // Log all response details .extract().response(); System.out.println("Response Status Code: " + response.getStatusCode()); } }
To integrate REST Assured with a test framework like TestNG or JUnit, include the REST Assured library in your project dependencies and write test methods using REST Assured.
For example, in a Maven project, add the REST Assured dependency in your pom.xml
file:
<dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>4.4.0</version> <scope>test</scope> </dependency>
Example with JUnit:
import io.restassured.RestAssured; import io.restassured.response.Response; import org.junit.Test; import static org.junit.Assert.assertEquals; public class ApiTest { @Test public void testGetEndpoint() { Response response = RestAssured.get("https://jsonplaceholder.typicode.com/posts/1"); assertEquals(200, response.getStatusCode()); } }
Example with 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 testGetEndpoint() { Response response = RestAssured.get("https://jsonplaceholder.typicode.com/posts/1"); Assert.assertEquals(response.getStatusCode(), 200); } }
Basic Authentication involves sending the username and password encoded in Base64 as part of the HTTP request header. In REST Assured, use the auth().basic()
method.
Example:
import io.restassured.RestAssured; import io.restassured.response.Response; public class BasicAuthExample { public static void main(String[] args) { Response response = RestAssured .given() .auth() .basic("username", "password") .when() .get("https://example.com/api/endpoint"); System.out.println("Response Code: " + response.getStatusCode()); } }
OAuth Authentication in REST Assured involves obtaining an access token and using it to authenticate API requests.
Example:
import io.restassured.RestAssured; import io.restassured.response.Response; public class OAuthExample { public static void main(String[] args) { // Step 1: Obtain the access token Response response = RestAssured.given() .formParam("client_id", "your_client_id") .formParam("client_secret", "your_client_secret") .formParam("grant_type", "client_credentials") .post("https://oauth.provider.com/token"); String accessToken = response.jsonPath().getString("access_token"); // Step 2: Use the access token to authenticate API requests RestAssured.given() .auth() .oauth2(accessToken) .get("https://api.yourservice.com/endpoint") .then() .statusCode(200); } }
Data-driven testing separates test data from test scripts, allowing the same test to run multiple times with different data sets. In REST Assured, implement this by reading test data from external sources and using it to drive API tests.
Example:
import io.restassured.RestAssured; import io.restassured.response.Response; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class DataDrivenTest { @DataProvider(name = "testData") public Object[][] createTestData() { return new Object[][] { {"data1", "expectedResult1"}, {"data2", "expectedResult2"}, {"data3", "expectedResult3"} }; } @Test(dataProvider = "testData") public void testAPI(String inputData, String expectedResult) { Response response = RestAssured.given() .param("data", inputData) .when() .get("http://example.com/api"); response.then().assertThat().statusCode(200); // Additional assertions based on expectedResult } }
In this example, the @DataProvider
annotation supplies test data to the test method, allowing for comprehensive API testing.