• Articles
  • Tutorials
  • Interview Questions

REST Assured Interview Questions

CTA

This blog consists of a combination of basic as well as challenging questions specifically created for REST Assured interview preparation. While giving your interview, keep the following tips in mind:

  • Research the company and the job role well.
  • Be prepared to discuss your major achievements and career milestones, particularly those relevant to REST Assured and API testing.
  • Prepare a list of questions about the role, team, company culture, and growth opportunities.
  • Maintain eye contact, smile, and use open body language during the interview to demonstrate your enthusiasm and interest in the role.
  • Pay close attention to each question. It’s okay to take a brief pause to think or to ask for clarification if a question isn’t clear, especially on technical aspects.
  • When discussing your skills and experiences, provide specific examples, particularly those involving REST Assured or similar tools.
  • Be honest about your skills and experiences. Don’t exaggerate or claim expertise in areas where you’re not confident.

This blog about REST Assured interview questions is categorized into three parts:

  1. Basic REST Assured Interview Questions for Freshers
  2. Intermediate REST Assured Interview Questions
  3. Advanced REST Assured Interview Questions for Experienced

Apart from these points, you need to keep a lot more things in mind while giving an interview. Watch the video below to figure out those golden tips.

Video Thumbnail

Let’s begin with the basic questions. They might sound too obvious, but that makes them important for freshers. Answering these questions correctly will help you land the job efficiently.

Basic REST Assured Interview Questions for Freshers

1. What is REST Assured?

REST Assured is an open-source Java library that provides a domain-specific language to write powerful automated tests for RESTful APIs. It offers a set of APIs that allow developers to easily test REST services without needing to write code from scratch. RESTful API and REST services enable networked applications to interact with resources adhering to the principles of REST.

2. How do you add REST Assured to your project?

REST Assured can be added to a project using tools like Maven or Gradle. We can include the dependency in the project’s pom.xml (Maven) or build.gradle (Gradle) file. For example, in a Maven project, we add the following to the pom.xml:

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>4.4.0</version>
    <scope>test</scope>
</dependency>

3. Explain the main components of a REST Assured test script.

The main components of a REST Assured test script are:

  • Base URL: The base URL for the REST API
  • Request Specification: Used to construct the request details like method, path, headers, body, etc.
  • Validation: Assertions to validate response status code, headers, body, etc.

4. What are the various HTTP methods supported by REST Assured?

All of the common HTTP methods used in RESTful API architecture are supported by REST Assured, which are:

  • GET: Used for retrieving data from a specified resource.
  • POST: Used for submitting data to be processed to a specified resource.
  • PUT: Used for updating a resource or creating a new resource if it doesn’t exist.
  • DELETE: Used for requesting the removal of a resource.
  • PATCH: Used for applying partial modifications to a resource.
  • OPTIONS: Used for describing the communication options for the target resource.
  • HEAD: Similar to GET but retrieves only the headers, not the actual data.

5. How do you send a GET request using REST Assured?

To send a GET request, we use the get() method provided by REST Assured. 

For example,

Response response = given().when().get("/api/resource");

6. Explain REST Assured method chaining.

REST Assured is like a tool for checking if web services (websites that communicate with each other) are working correctly. It’s made using the Java programming language. One cool thing about it is that you can use a technique called method chaining. This means you can link different actions together, making it easier to write and understand the instructions for checking the web services. So, when you make requests to a website, and you need to include lots of details like parameters or headers, method chaining in REST Assured helps keep things organized and easy to follow.

7. Explain the difference between 'given()', 'when()', and 'then()' in REST Assured.

given(): Sets up preconditions (e.g., base URI, headers, parameters).

when()
    .get("/api/resource");

when(): Specifies the action (HTTP method and endpoint).

when()
    .get("/api/resource");

then(): Defines expected outcomes (e.g., status code, response body).

given()
    .baseUri("https://api.example.com")
    .header("Content-Type", "application/json")
    .param("key", "value")
.when()
    .get("/api/resource")
.then()
    .statusCode(200)
    .body("data.name", equalTo("John Doe"));

8. What is the request specification, and how is it initiated?

In REST Assured, the request specification is initiated using ‘given()’. It’s a starting point for setting up details like base URI, headers, and parameters before making an API call. 

For example,

given()
    .baseUri("https://api.example.com")
    .header("Content-Type", "application/json")
    .param("key", "value")
.when()
    .get("/api/resource")
.then()
    .statusCode(200);

Preparing for testing jobs? Check out our list of most asked Manual Testing Interview Questions.

Get 100% Hike!

Master Most in Demand Skills Now !

9. How do you handle authentication in REST Assured?

In REST Assured, you can handle authentication using various methods, depending on the type of authentication required. Here are two common approaches:

  • Basic Authentication: Use the auth().basic(username, password) method to include basic authentication in your request.

Example:

given()
    .baseUri("https://api.example.com")
    .auth().basic("username", "password")
.when()
    .get("/api/resource")
.then()
    .statusCode(200);
  • Bearer Token Authentication: If your API requires a bearer token, use the auth().oauth2(token) method.

Example:

given()
    .baseUri("https://api.example.com")
    .auth().oauth2("yourBearerToken")
.when()
    .get("/api/resource")
.then()
    .statusCode(200);

10. What is the role of the 'baseURL' and 'basePath' methods in REST Assured?

In REST Assured, the ‘baseURI’ and ‘basePath’ methods are used to define the base URL and base path for your API requests. 

  • ‘baseURI’(String baseUri) Method:

Role: Specifies the base URL for the API.

Example:

given()
    .baseUri("https://api.example.com")
.when()
    .get("/api/resource")
.then()
    .statusCode(200);
  • ‘basePath’(String basePath) Method:

Role: Specifies the base path for the API.

Example:

given()
    .baseUri("https://api.example.com")
    .basePath("/v1")
.when()
    .get("/resource")
.then()
    .statusCode(200);

Using these methods, you can set the common base URL and path for multiple requests, reducing redundancy in your test code.

Intermediate REST Assured Interview Questions

11. How do you validate responses in REST Assured?

Responses in REST Assured can be validated using various assertions provided by the library. For instance, you can verify the status code, response time, content type, and response body. This is typically done using the then() method, where you can chain assertions like statusCode(200) or body(“key”, equalTo(“value”)).

12. Describe how to extract data from a response in REST Assured.

Data can be extracted from a response using the extract() method. This allows you to retrieve specific parts of the response, such as headers, cookies, or body, and store them in variables for further use.

For example, String value = response.extract().path(“key”) extracts a value associated with a specific key from the JSON response.

13. What is GPath in REST Assured, and how is it used?

GPath is a syntax used in REST Assured for extracting and asserting data from a response. It’s similar to XPath for XML and allows for easy navigation within JSON responses. GPath expressions can be used with the path() method to retrieve specific elements from the response.

14. Explain how to handle parameters in REST Assured.

Parameters in REST Assured can be handled using methods like param(), queryParams(), and formParams(). These methods allow you to add parameters to your request, whether they are query parameters, form parameters, or path parameters.

15. How do you manage cookies in REST Assured?

Cookies can be managed using the ‘cookie()’ method for adding cookies to requests and the ‘cookies()’ method for extracting cookies from responses. REST Assured also allows for detailed cookie specifications, including setting their name, value, path, and expiry.

16. Discuss the use of filters in REST Assured.

Filters in REST Assured are used to intercept and modify requests and responses. They can be used for logging, authentication, or custom modifications of the request/response cycle. Filters can be added globally or on a per-request basis.

17. What is JSONPath in REST Assured, and how do you use it?

JSONPath is a query language for JSON, similar to XPath for XML. In REST Assured, JSONPath expressions are used to extract specific parts from a JSON response. This is done using the ‘JsonPath’ class or the ‘path()’ method in the response.

18. How do you perform path parameterization in REST Assured?

Path parameterization in REST Assured is done using the ‘pathParam()’ method. This allows for dynamic URLs where certain parts of the path can be set at runtime. For example, given().pathParam(“id”, 123).when().get(“/users/{id}”).

19. Explain the concept of serialization and deserialization in REST Assured.

Serialization in REST Assured refers to converting a Java object into a JSON or XML payload to send with a request. Deserialization is the opposite, where a JSON or XML response is converted back into a Java object. This is typically handled automatically by REST Assured using libraries like Jackson or Gson.

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

REST Assured can be integrated with TestNG or JUnit by simply writing REST Assured code within TestNG/JUnit test methods. Assertions in REST Assured can be combined with TestNG/JUnit assertions to create comprehensive API tests.

It involves a few steps, like adding dependencies, writing Test Class, and running Test.

Integrating REST Assured with TestNG:

Add Dependencies in pom.xml:

<dependencies>
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>4.4.0</version>          # Use the latest version available
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.3.0</version>          #Use the latest version available
        <scope>test</scope>
    </dependency>
</dependencies>

Write Test Class:

import io.restassured.RestAssured;
import org.testng.annotations.Test;
public class RestAssuredTestNGExample {
    @Test
    public void testGetRequest() {  
        RestAssured.given()
            .when()
            .get("https://jsonplaceholder.typicode.com/posts/1")
            .then()
            .statusCode(200);
    }

Run Tests:

Use any method to run TestNG tests.

Integrating REST Assured with JUnit:

Add Dependencies in pom.xml:

<dependencies>
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>4.4.0</version> 
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>5.8.2</version>          
        <scope>test</scope>
    </dependency>
</dependencies>

Write Test Class:

import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
public class RestAssuredJUnitExample {
    @Test
    public void testGetRequest() {
        // Your REST Assured code for GET request
        RestAssured.given()
            .when()
            .get("https://jsonplaceholder.typicode.com/posts/1")
            .then()
            .statusCode(200);
    }

Run Tests:

Execute your JUnit tests.

21. Discuss the importance of the ContentType enum in REST Assured.

The ContentType enum in REST Assured is used to specify the content type of the request and response. It’s important to ensure that the API correctly interprets the data format being sent and received, such as JSON, XML, or HTML.

22. Explain how to log requests and responses in REST Assured.

Logging in REST Assured can be done using the ‘log()’ method. You can log requests, responses, or both, and it can be configured to log only when the test fails. This is useful for debugging and verifying the details of API interactions.

23. What are the common assertions used in REST Assured?

Common assertions in REST Assured include checking the status code (‘statusCode’), content type (‘contentType’), body content (‘body’), headers, and response time. These assertions are used to validate different aspects of the response.

24. How do you handle SSL/TLS certificates in REST Assured?

SSL/TLS certificates can be handled in REST Assured by configuring the SSL context or using methods like ‘relaxedHTTPSValidation()’ for less stringent validation, which is useful in testing environments.

25. Explain the use of the 'extract()' method in REST Assured.

The ‘extract()’ method is used to extract details from the response, such as headers, cookies, body, and path parameters. This is useful for scenarios where you need to use data from a response in subsequent requests or assertions.

Advanced REST Assured Interview Questions for Experienced

26. What exactly is 'client-server architecture?'

The client-server architecture model explains how a server shares services and resources with one or more clients. Servers, such as mail servers, data centers, and web servers, are examples of this. So, when a client asks for something, the server provides it.

Client Server Architecture

 

27. Discuss the architecture of REST Assured and its integration with other Java libraries.

To handle complex JSON structures in REST Assured, you can implement custom serializers and deserializers using Jackson or Gson. Here’s a brief overview using Jackson:

Define Custom Serializer/Deserializer:

  • Create classes extending StdSerializer and JsonDeserializer from Jackson.
  • Implement custom serialization and deserialization logic within these classes.

Configure ObjectMapper:

  • Instantiate Jackson’s ObjectMapper.
  • Register your custom serializer and deserializer to the ObjectMapper using SimpleModule.

Integrate with REST Assured:

  • Set REST Assured’s objectMapperFactory to use your custom-configured ObjectMapper.
  • This ensures REST Assured uses your custom serializer/deserializer for API requests and responses.

Example Snippet:

ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(MyClass.class, new MyCustomSerializer());
module.addDeserializer(MyClass.class, new MyCustomDeserializer());
objectMapper.registerModule(module);
RestAssured.objectMapperFactory = (type, s) -> objectMapper;

This setup is particularly useful for complex JSON structures that require specific parsing or formatting not covered by default serializers/deserializers.

28. How do you implement OAuth 2.0 authentication in REST Assured?

To implement OAuth 2.0 authentication in REST Assured in a simpler way, follow these steps:

Obtain the OAuth 2.0 Token:

  • First, you need to get an access token from the OAuth 2.0 provider. This usually involves making a request to the token endpoint of the OAuth server with your client credentials.

Use the Token in REST Assured Requests:

  • Once you have the access token, you can use it in your REST Assured requests. This is typically done by adding the token to the Authorization header as a Bearer token.

Here’s a basic example:

// Obtain the OAuth 2.0 access token (this part depends on your OAuth server)
String accessToken = "your_access_token";
// Use the token in REST Assured requests
given()
  .auth()
  .oauth2(accessToken)
  .when()
  .get("/your_api_endpoint")
  .then()
  .statusCode(200);

In this example, replace “your_access_token” with the actual token you obtained, and “/your_api_endpoint” with the API endpoint you want to test. This setup ensures that all requests made with REST Assured are authenticated using the OAuth 2.0 token.

29. Explain advanced JSON and XML parsing techniques in REST Assured.

Advanced JSON Parsing:

Using JSONPath for Complex Queries:

  • JSONPath is like XPath for JSON and lets you navigate through elements and structures within a JSON document.
  • You can extract values, arrays, or even perform conditional searches.

Example:

String response = given().when().get("/api").asString();
JsonPath jsonPath = new JsonPath(response);
String value = jsonPath.getString("data[0].name"); // Extracts the name from the first element in a data array.

Handling Nested JSON Objects:

  • For deeply nested structures, you can chain the queries or use a more complex JSONPath expression.

Example:

String nestedValue =
jsonPath.getString("data[0].details.address.street");

Advanced XML Parsing:

Using XmlPath for XML Data:

  • XmlPath allows you to navigate and extract data from XML responses.
  • You can retrieve attributes, text values, or even apply filters.

Example:

String xmlResponse = given().when().get("/api/xml").asString();
XmlPath xmlPath = new XmlPath(xmlResponse);
String value = xmlPath.getString("user.@id"); // Extracts the 'id' attribute of a 'user' element.

Handling Complex XML Structures:

  • For complex XML with nested elements, use a path that navigates through the hierarchy.

Example:

String nestedValue =
xmlPath.getString("users.user[0].address.street");

In both JSON and XML parsing, REST Assured provides a way to navigate through complex and nested data structures, allowing you to extract specific pieces of data needed for your tests. The key is understanding the structure of your JSON/XML and using the correct path syntax to access the data.

30. Discuss the handling of multipart file uploads in REST Assured.

Handling multipart file uploads in REST Assured involves sending a request where one or more files are included in the payload along with other form data. This is common in scenarios where you’re testing endpoints for uploading documents, images, or other file types. Here’s the explanation:

Use the multiPart Method:

  • REST Assured provides the multiPart method to handle file uploads.
  • You specify the file along with the form field name that the server expects.

Include Other Form Data (if needed):

  • If your API endpoint requires additional form data along with the file, you can add it using the formParam method.

Send the Request:

  • Finally, send your request to the server using the appropriate HTTP method (usually POST).

Here’s a simple example:

File fileToUpload = new File("path/to/your/file.txt");
given()
  .multiPart("file", fileToUpload)
  .formParam("additionalParam", "value") // Add other form fields if needed
  .when()
  .post("/upload_endpoint")
  .then()
  .statusCode(200); // Check for successful upload

31. How do you customize and extend REST Assured functionalities?

Customizing and extending REST Assured can be achieved in several ways to suit specific testing needs. Here are the key methods:

  • Custom Filters: We can create custom filters by implementing the Filter interface. This allows us to intercept and modify requests and responses. For example, we might add a filter to log all requests and responses in a specific format or add common headers to every request.
  • Custom Matchers: For more tailored assertions, we can develop custom Hamcrest matchers. This is particularly useful when the standard matchers provided by REST Assured or Hamcrest don’t meet our specific validation requirements.
  • Request and Response Specifications: To standardize our API tests and reduce code duplication, we can use RequestSpecBuilder and ResponseSpecBuilder. These builders help create reusable request and response specifications that can be used across multiple tests.
  • Integration with Other Libraries: REST Assured can be integrated with other Java libraries for enhanced functionality. For instance, we might use advanced JSON processing libraries if we need more complex JSON manipulation than what’s provided out of the box.

An example of a custom filter might look like this:

public class MyCustomFilter implements Filter {
    @Override
    public Response filter(FilterableRequestSpecification requestSpec,
                           FilterableResponseSpecification responseSpec,
                           FilterContext ctx) {
        // Custom logic to modify the request or response
        return ctx.next(requestSpec, responseSpec);
    }
}
// Usage in a test
given()
  .filter(new MyCustomFilter())
  .when()
  .get("/someEndpoint")
  .then()
  .statusCode(200);

32. Explain the use of RequestSpecification and ResponseSpecification for reusable tests.

In REST Assured, RequestSpecification and ResponseSpecification are powerful features that allow for creating reusable templates for API requests and responses. This helps in making the test code more organized and readable and reduces redundancy. Let me explain each one:

RequestSpecification:

  • ‘RequestSpecification’ is used to create a template for an API request. It can include common request parameters such as headers, query parameters, body content, and authentication details.
  • By using ‘RequestSpecification’, we can define a standard setup for our API requests, which can then be reused across multiple tests. This is particularly useful when many API endpoints share similar request configurations.

Example:

RequestSpecification commonRequestSpec = new
RequestSpecBuilder()
    .setBaseUri("http://api.example.com")
    .addHeader("Content-Type", "application/json")
    .build();
given()
    .spec(commonRequestSpec)
    .body(someRequestBody)
    .when()
    .post("/endpoint")
    .then()
    .statusCode(200);

In this example, ‘commonRequestSpec’ is a reusable request specification that sets the base URI and content type, which is used in multiple tests.

ResponseSpecification:

  • Similarly, ResponseSpecification allows us to define a standard template for API responses. This can include expected status codes, response time, headers, and body content.
  • It helps in asserting common response attributes and ensures consistency in how responses are validated.

Example:

ResponseSpecification commonResponseSpec = new ResponseSpecBuilder()
    .expectStatusCode(200)
    .expectContentType(ContentType.JSON)
    .build();
given()
    .spec(commonRequestSpec)
    .when()
    .get("/someEndpoint")
    .then()
    .spec(commonResponseSpec);

Here, ‘commonResponseSpec’ is a reusable response specification that checks for a status code of 200 and a JSON content type.

33. How do you perform data-driven testing using REST Assured?

Data-driven testing in REST Assured can be done by feeding multiple sets of data into the same test. This is usually achieved by integrating REST Assured with a testing framework like TestNG or JUnit. Here’s a simple way to do it:

  • First, prepare your test data. This could be in the form of an array, a list, or external files like CSV, JSON, or XML.
  • Use a testing framework like TestNG or JUnit. These frameworks have features for data-driven testing, such as TestNG’s @DataProvider annotation.
  • Create a test method that accepts data.
  • The testing framework will automatically run your test method with each set of data you’ve provided.

Here’s a basic example using TestNG:

@DataProvider(name = "userData")
public Object[][] createUserData() {
    return new Object[][] {
        {"user1", "password1"},
        {"user2", "password2"}
    };
}
@Test(dataProvider = "userData")
public void testLogin(String username, String password) {
    given()
        .param("username", username)
        .param("password", password)
        .when()
        .post("/login")
        .then()
        .statusCode(200);
}

In this example, the ‘testLogin’ method will run twice, once with ‘{“user1”, “password1”}’ and once with ‘{“user2”, “password2”}’. This approach allows us to test different scenarios with various data sets.

34. Explain the integration of REST Assured with CI/CD pipelines.

Integrating REST Assured with CI/CD pipelines is straightforward because it’s a Java-based framework and fits well into standard Java project workflows. Here’s a brief overview:

  • Write Tests in REST Assured: First, you write your API tests using REST Assured in your Java project.
  • Build Tool Configuration: Ensure your project’s build tool, like Maven or Gradle, is set up to run these tests. This typically involves configuring the build script to execute tests during the build process.
  • CI/CD Pipeline Setup: In your CI/CD tool (like Jenkins, GitLab CI or GitHub Actions), configure a pipeline that checks out your code, runs the build tool, and executes the REST Assured tests as part of the build.
  • Test Reports and Feedback: After tests are executed, the CI/CD tool can be configured to generate reports and provide feedback. If tests fail, the pipeline can halt, preventing the deployment of faulty code.
  • Automated Triggers: You can set up the pipeline to be triggered automatically on code commits or at scheduled intervals.

REST Assured tests are run as part of the build process in the CI/CD pipeline. Make sure that API tests are automatically and consistently executed, contributing to the overall quality and reliability of the software delivery process.

35. Discuss the use of REST Assured in microservices testing.

REST Assured is a powerful testing library for API testing, and it’s particularly handy in the context of microservices. In simpler terms, it helps us check if different parts of our microservices can talk to each other properly.

Imagine you have a bunch of mini-applications (microservices) that need to share information. REST Assured acts like a detective, making sure they’re passing messages correctly. It sends requests to these microservices and checks if the responses are what we expect.

So, in microservices testing, REST Assured plays the role of a trustworthy messenger, ensuring that our microservices communicate effectively without any hiccups.

36. How do you handle dynamic responses in REST Assured?

Handling dynamic responses in REST Assured is crucial for dealing with changing data or unpredictable server responses. Here are some techniques:

Use of Placeholder Values: Replace dynamic parts of the response with placeholder values, like using any() for unpredictable data.

given().get("/api/user")
.then().body("name", any(String.class));

JSONPath and XPath Expressions: Leverage JSONPath or XPath expressions to extract specific values from the response, even if the structure varies.

String dynamicValue = get("/api/user").path("some.element[0].value");

Response Object and Assertions: Capture the entire response and then assert on specific fields. This way, dynamic parts won’t affect the overall test.

Response response = get("/api/user");
assertEquals("Expected Value",
response.jsonPath().get("dynamicField"));

Using Matchers for Collections: When dealing with dynamic lists, use Hamcrest matchers to check if certain elements are present without worrying about the order.

given().get("/api/users")
.then().body("users", hasItem("John Doe"));

These methods help handle variability in responses and make sure that tests remain robust even when dealing with dynamic data.

37. Explain the significance of the RestAssured.config() method.

The ‘RestAssured.config()’ method in RestAssured is significant because it allows you to configure various settings and behaviors for your API tests. This method returns an instance of the ‘RestAssuredConfig’ class, which you can use to customize the behavior of RestAssured for your specific needs.

  • Default Configuration: You can use RestAssured.config() to set default configurations for all requests. For example, you might want to set a default base URI or authentication method for all your API requests.
  • SSL Configuration: It allows you to configure SSL settings, such as trusting self-signed certificates or specifying a keystore.
  • Object Mapping Configuration: You can customize how RestAssured maps JSON or XML responses to Java objects using RestAssuredConfig. This is useful when dealing with complex or custom serialization/deserialization scenarios.
  • Timeouts and Connection Settings: Configure timeouts for requests, specifying how long to wait for a response or connection.

Here’s a simple example of how you might use RestAssured.config():

RestAssured.config = RestAssuredConfig.config()
    .sslConfig(SSLConfig.sslConfig().allowAllHostnames())
    .objectMapperConfig(ObjectMapperConfig.objectMapperConfig().defaultObjectMapperType(ObjectMapperType.GSON));

In this example, it configures RestAssured to trust all hostnames for SSL and use the GSON library for object mapping. The RestAssured.config() method allows you to fine-tune RestAssured’s behavior according to the requirements of your API testing scenarios.

38. Discuss advanced error handling and debugging techniques in REST Assured.

Advanced error handling and debugging are crucial aspects of API testing with REST Assured. Here are some techniques to enhance error handling and debugging:

  • Logging for Details: Use log().all() to print request and response details, aiding in quick issue identification.
given().log().all().get("/api/endpoint").then().log().all();
  • Extract for Analysis: Leverage ValidatableResponse to extract specific response parts for detailed error analysis.
ValidatableResponse response = given().get("/api/endpoint").then();
String errorDetails = response.extract().body().asString();
  • Soft Assertions: Implement soft assertions to capture multiple issues in a single test run.
SoftAssertions softAssert = new SoftAssertions();
softAssert.assertThat(response.statusCode()).isEqualTo(200);
softAssert.assertThat(response.body("attribute", equalTo("expectedValue")));
softAssert.assertAll();
  • Custom Error Messages: Provide clear error messages for quick issue identification in failed assertions.
given().get("/api/endpoint")
.then().assertThat().statusCode(200).withFailMessage("Expected status code: 200");
  • Error Handling Filters: Use filters for custom actions on specific responses.
given().get("/api/endpoint")
.then().statusCode(200)
.filters((response, filterContext) -> {
    if (response.statusCode() != 200) {
        // Custom actions for non-200 responses
    }
});
  • Debugging with Breakpoints: Set breakpoints strategically for step-by-step debugging during test execution.

39. How do you test GraphQL APIs using REST Assured?

Testing GraphQL APIs with REST Assured involves a slightly different approach compared to traditional REST APIs, mainly because GraphQL typically uses a single endpoint with varying query or mutation requests. Here’s how you can do it:

Set Up the Request

  • Since GraphQL requests are usually POST requests with a JSON payload, you’ll set up your request in REST Assured accordingly.
  • The JSON payload typically contains at least two fields, query (or mutation) and optionally variables.

Specify the GraphQL Query or Mutation

  • Write the GraphQL query or mutation as a String. This is similar to what you would send in a GraphQL client.
  • If your query uses variables, define them in the variables field of your JSON payload.

Send the Request and Validate the Response

  • Use REST Assured to send the request to the GraphQL endpoint and validate the response.
  • The response validation can include checking the status code, the structure of the JSON response, and the values returned.

Here’s a basic example:

String graphqlPayload = "{ \"query\": \"{ user(id: 1) { name, email } }\" }";
given()
  .contentType(ContentType.JSON)
  .body(graphqlPayload)
  .when()
  .post("/graphql")
  .then()
  .statusCode(200)
  .body("data.user.name", equalTo("John Doe"));

In this example, we’re sending a query to fetch a user’s name and email. The ‘given(‘) method sets up the request with the appropriate content type and body, and the ‘then()’ method asserts the response.

Want to learn more about Selenium? Check out our Selenium Tutorial.

40. Can you explain the difference between PUT and POST methods in API testing?

The difference between PUT and POST methods in API testing is primarily about how they are used to handle resource data.

Aspect POST Method PUT Method
Purpose Used to create a new resource. Used to update an existing resource or create a new one at a specific URL.
Idempotency Non-idempotent (performing the same request multiple times can create multiple resources). Idempotent (performing the same request multiple times results in the same state).
Example POST /articles (creates a new article) PUT /articles/123 (updates or creates article with ID 123)

Course Schedule

Name Date Details
Python Course 05 Oct 2024(Sat-Sun) Weekend Batch
View Details
Python Course 12 Oct 2024(Sat-Sun) Weekend Batch
View Details
Python Course 19 Oct 2024(Sat-Sun) Weekend Batch
View Details

About the Author

Technical Research Analyst - Deep Learning

As a Technical Research Analyst specializing in Deep Learning, Aditya combines expertise in Python with a keen interest in cutting-edge technologies. He possesses a year of experience in designing and deploying robust applications. Additionally, he is passionate about writing and conveying complex technical concepts with clarity and precision.