Interview

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.

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 API Automation Interview Questions and Answers

1. What is REST Assured and why is it used?

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.

2. Explain how to send a GET request.

To send a GET request using REST Assured, follow these steps:

  • Set up the base URI for the RESTful web service.
  • Use the given() method to specify the request details.
  • Use the when() method to specify the HTTP method (GET in this case).
  • Use the then() method to validate the response.

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.

3. How can you validate the status code of a response?

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);
        }
    }
}

4. Describe how to handle query parameters in a request.

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.

5. Explain how to send a POST request with a JSON body.

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());
    }
}

6. How can you extract values from a JSON response?

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.

7. Describe how to handle path parameters.

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.

8. Explain how to set headers in a request.

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.

9. Describe how to log request and response details.

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.

10. Explain how to use filters.

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);
    }
}

11. Explain how to integrate tests with a CI/CD pipeline.

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:

  • Version Control System (VCS): Ensure that your REST Assured test scripts are stored in a version control system like Git.
  • CI/CD Tool Configuration: Use a CI/CD tool such as Jenkins, GitLab CI, or CircleCI. Configure the tool to trigger builds and test executions based on specific events.
  • Build Script Setup: Create a build script (e.g., a Maven or Gradle script) that compiles your test code and runs the REST Assured tests.
  • Pipeline Definition: Define your CI/CD pipeline in the CI/CD tool, specifying the stages of the pipeline, such as build, test, and deploy.
  • Test Execution Stage: Add a stage in the pipeline configuration for executing the REST Assured tests.
  • Reporting and Notifications: Configure the CI/CD tool to generate test reports and send notifications based on the test results.
  • Environment Management: Ensure that the necessary environment is available and properly configured for the tests to run.

12. How can you extend REST Assured with custom matchers or assertions?

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.

13. What strategies do you use for error handling in REST Assured tests?

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());
        }
    }
}

14. How do you integrate REST Assured with TestNG or JUnit?

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"));
    }
}

15. What are some best practices for writing REST Assured tests?

When writing REST Assured tests, follow these best practices to ensure your tests are maintainable, readable, and effective:

  • Use Descriptive Test Names: Ensure that your test names clearly describe what the test is verifying.
  • Organize Tests Logically: Group related tests together and use a consistent structure for your test classes.
  • Parameterize Tests: Use parameterized tests to run the same test with different inputs.
  • Use Constants for Repeated Values: Define constants for values that are used multiple times in your tests.
  • Validate Responses Thoroughly: Ensure that your tests validate not only the status code but also the response body, headers, and other relevant aspects of the response.
  • Handle Authentication and Authorization: If your API requires authentication, ensure that your tests handle this correctly.
  • Use Data-Driven Testing: Store test data in external files and load this data into your tests.
  • Clean Up After Tests: Ensure that any data created during a test is cleaned up afterwards.
  • Use Assertions Wisely: Use clear and meaningful assertions to verify the expected outcomes.
  • Log and Report Results: Implement logging and reporting mechanisms to capture test results and any relevant information.
Previous

15 MS Word Interview Questions and Answers

Back to Interview
Next

10 Verilog Design Interview Questions and Answers