Skip to content

Latest 30+ Rest Assured Interview Questions

API Testing Interview Questions

In this article, we will cover important Rest Assured Interview Questions for Automation Engineer. In a competitive job market, having knowledge of Rest Assured and being able to answer related interview questions can give you an edge over other candidates

Table of Contents

1) What is Rest-Assured?

Rest Assured is an open-source Java-based library used for testing Restful APIs.

2)Why should you Use Rest Assured Over Postman for Automated Testing?

Both Postman and Rest Assured have their advantages and disadvantages: I choose Rest Assured because it is a Java DSL hence code can be designed in such a way as to maintain reusability, the more the reusability, the lesser the maintenance cost. Scripts can be designed using a behaviour-driven approach or a data-driven approach per the requirements. Reports can be customized but it is not possible in Postman.

3)How does Rest Assured work internally?

Rest assured internally uses Groovy language. Groovy comes with a path expression language called GPath. it is used to extract responses and works for both XML and JSON.

4)How to add Rest Assured to a Maven project?

To Add Rest Assured in Maven project add below mentioned dependency in pom.xml.

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

5)How to send a GET request using Rest Assured?

Get is the HTTP method that is used to fetch the information from the server.

RestAssured.given().baseUri("http://localhost:4001").when().get("/endpoint").then().statusCode(200)

RestAssured.given() method is used to set up the preconditions for the request. Here we are providing the base URL using the base URI() method.

When() is used to specify the action to be performed, it shows that a GET request will be made to resource ‘/endpoint’.

then() It is used to perform assertions or validations on the response.

statusCode() is the verification point to assert whether the condition was successfully met or not.

6)How to log response in Rest Assured only in the case of an error.

User ifError() method. It Logs everything only if an error occurs.

public void logOnlyIfError()
{
 
 RestAssured.given().baseUri("http://localhost:4001")
  .contentType(ContentType.JSON).log().all().when().get("/users").
                 then().log().ifError().assertThat().statusCode(200);
 }

7)How to mask header information in API testing?

From Rest Assured version 4.2.0 we can hide header information by blacklisting it so that it will not be shown in the request or response log.

given().config(config().logConfig(logConfig().blacklistHeader("apikey"))). ..

see the response image below for reference.

Masking Header information
Blacklist Header

To mask multiple headers create a set of headers and pass the collection in the blacklistHeaders() method.

Set<String> headers= new HashSet();
	headers.add("x-api-key");
	headers.add("secreat key");
         RestAssured.given().config(config().logConfig(logConfig()
           .blacklistHeaders(headers)));

8)How to send multivalue headers in Rest Assured?

Rest Assured supports sending multiple header values in the header method.

RestAssured.given().baseUri("http://localhost:5001")
.header("multivalue header","value1","value2")
.log().headers().when().get("/users")
.then().log().ifError().assertThat().statusCode(200);

9)Explain different ways of extracting a single field from a response body.

1)Use the Response object

RequestSpecification request = RestAssured.given();
 Response resp=request.baseUri("http://localhost:4001")
  .header("multivalueheader","value1","value2").log().headers()
  .when().get("/users").then().assertThat().statusCode(200).extract().response();
   System.out.println(resp.path("users[0].name"));

2)By Using the JsonPath Class

The JsonPath class is part of the Rest Assured library which allows us to work with JSON path expressions to extract specific values using a concise and readable syntax.

JsonPath jpath=new JsonPath(resp.asString());
System.out.println(jpath.getString("users[0].name"));

10)How to validate the response time of the request using rest assured?

The response time of the request can be measured using a simple long matcher.

RestAssured.given().baseUri("http://localhost:4001").contentType(ContentType.JSON).log().all()
.when().get("/users").then().time(lessThan(5000L)

11)What is the difference between path params and query params and how to use them?

Path params are used to identify resources on the server while query params are used to sort/filter resources. Query params are key-value-like pairs that appear after the question mark in the URL while path params come before the question mark.

How to pass Path Param:

@Test
void test() {
	RestAssured.given()
	.pathParam("user", "users/qaautomatonhub")
	.when()
	.get("https://http://localhost:4001/{user}")
	.prettyPrint();
}

How to pass query Param:

 public void verifyRepos(){
        
      <meta charset="utf-8">RestAssured.given()
          .queryParam("sort","created")
          .queryParam("direction","desc")
          .when().get("<meta charset="utf-8">https://http://localhost:4001/users")
          .then().log().body();
    }

12)Explain the Request specification and response in Rest Assured.

Request Specification and Response both are rest assured interfaces. Request specification allows specifying how the request will look like. The request Specification Interface has methods to define the base URL, base path, headers, body, etc. The response interface extends the ResponseBody, and ResponseOptions interfaces and is used to return a response to the request.

13)How to perform Basic Authentication in Rest Assured?

Basic authentication is used to ensure that only the authorized users can access/View the API’s.

RestAssured.given().auth().basic(username, password)

This is the simplest form of authentication which uses only a username and password encoded in base 64 format.

14)How to download a file using rest assured?

We can download the file as a Byte Array.

public void test() {
    byte[] dowloadedFile = RestAssured.given()
    .when().get("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&thumbs=True")		 
    .then().extract().asByteArray();
    System.out.println("Download File Size : "+dowloadedFile.length);

15)How to upload a media file using Rest Assured?

public void upload() {
	File file = new File("myavatar.png");
	Response resp= RestAssured.given()
	.multiPart("media_url", file,"application/octet-stream").when()
        .post("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&thumbs=True")
       .then().extract().response();
	String url=resp.path("url");
	System.out.println(url);
}

16)How to perform API chaining(Pass value from one API to another API)?

We can pass data using the ITestContext interface of TestNG.This interface provides context or information about the execution of a test suite. This interface has 2 very useful methods getAttribute () and setAttribute(). With the help of these methods, we can set and get the values that will be used in API chaining.

@Test
public void createBooking(ITestContext context)
{
	int bookingId = RestAssured
	.given()
		.log()
		.all()
		.baseUri("https://restful-booker.herokuapp.com/")
		.basePath("booking")
		.contentType(ContentType.JSON)
		.body("booking.json")
		.when()
		.post()
		.then()
		.log()
		.all()
		.extract()
		.jsonPath()
		.get("bookingid");
		// Storing data in a context to use for other tests
		context.setAttribute("bookingId", bookingId);
	}
@Test
public void updateBooking(ITestContext context)
{
  int bookingId = (int) context.getAttribute("bookingId");
  RestAssured.given().log().all()
  .baseUri("https://restful-booker.herokuapp.com/")
  .basePath("booking/"+bookingId)
  .header("Authorization","Your token").contentType(ContentType.JSON)
  .body("booking.json").when().put().then().log().all();
  }

This interface can retrieve parameters defined at the suite level using the getSuite() method.

17)Can we write RestAssured.with() instead of RestAssured.given()? What is the difference?

Yes we can use any of the below-mentioned approaches like

RequestSpecification requestwith = RestAssured.with();

RequestSpecification requestgiven = RestAssured.given();

Both work in the same way, The only difference between {@link #with()} and {@link #given()} is syntactical.

18)How to send a Nested JSON object as a payload?

Ex: {“workspace”: {

“name”: “workspace”,

“id”: “X123”

}}

Create a hashmap and store objects in it. Refer to the below code.

HashMap<String,Object> mainobj= new HashMap()<String,Object>();
HashMap<String,String> subobj= new HashMap()<String,String>();
subobj.put("name","QA");
subobj.put("id","X123");
mainobj.put("workspace",subobj);

19)Write a code snippet to fetch cookies.

Rest Assured Interview Questions

20)Can you use rest assured with c#?

No, Rest assured is Java DSL. To use with c# we have RestSharp. Which is also an HTTP library.

21)How to validate XML response in rest assured?

To validate the XML response we need to use Content-Type as ‘ContentType.XML’ and need to import the following package

import io.restassured.path.xml.XmlPath;

Sample XML payload

<?xml version="1.0" ?>
<nresponse
    orderID="50143601"
    STATUS="5>
</nresponse>

The code should be like

String r = given().accept(ContentType.XML).when().get("/").thenReturn()
.asString();
 XmlPath x = new XmlPath(r);
System.out.println("Order Id: " + x.getString("nresponse.orderID"));

22)Why does Rest Assured use static import?

Static import is a feature of the Java programming language that allows you to use members such as fields and methods that were scoped as public static in their container class without naming the class in which they were defined.

23)How to do JSON schema Validation in API testing?

How to do JSON schema validation.

24)How do you handle timeouts in Rest Assured?

To handle timeouts, rest assured provides the timeout() method. We can provide the required value in this method while hitting the endpoint.

given().timeout(5000).when().get("https://api.example.com/users");

25)What is the purpose of the relaxedHTTPSValidation() method in the Rest Assured?

This method disables SSL/TLS certificate validation. It is useful for testing on environments with self-signed certificates.

26)How to check that a specific item is present in a collection using Rest Assured?

In Rest Assured, hasItem() function checks if a specified item exists in a collection. Example: .body("items", hasItem("value")).It is part of the Hamcrest Matcher Library.

       RestAssured
            .when().get(endpoint)
            .then()
            .statusCode(200)  // Assuming the response code is 200
            .body("items", Matchers.hasItem("text1"))  
            }

27)What is the purpose of the statusLine() method in response validation?

The statusLine()method in Rest Assured Library validates the entire status line of the response, including the HTTP version and status code.

 Assert.assertEquals(statusLine /*actual value*/, "HTTP/1.1 200 OK" 
      /*expected value*/, "Correct status code returned");

We can see in the above code snippet that the status line consists of [Http Protocol Version, Status Code, Status String].

28)Write code snippet for delete request.

Delete request is used to delete the resource from the server for the requested endpoint. It returns different response codes based on the action performed for example 202,204,200,404 etc.

RestAssured
            .given()
                .pathParam("resourceId", resourceIdToDelete)
            .when()
                .delete(endpoint)
            .then()
                .statusCode(204);  // Assuming that a successful DELETE request returns a status code of 204 (No Content)
    }

29) What is web socket API?

Web socket API is a type of API that supports bi-directional communication, unlike Rest API which supports only uni-directional communication. It is suitable for real-time applications as it stores data hence its stateful. These APIs are faster than the Rest APIs’ but are complex in nature.

30) What are the best practices for developing a maintainable Rest Assured Framework?

1)Separate test data, test logic, and assertions using a modular approach.
2)Reduce code duplication by implementing reusable helper methods or classes.
3)Variable and method names should be meaningful and descriptive.
4)To make troubleshooting easier, implement effective error handling and logging.