Table of contents
1.
Introduction
2.
REST Assured
3.
Advantages of REST Assured
4.
Disadvantages of REST Assured
5.
Expected Response in Rest Assured
5.1.
How The Expected Response is Defined
5.1.1.
Syntax
5.1.2.
Explanation
6.
ResponseSpecification in REST Assured
6.1.
Need for RequestSpecification in REST Assured
6.2.
Implementation in Java
6.2.1.
Output 
6.3.
Using ResponseSpecification
6.4.
Implementation in Java
6.4.1.
Output
7.
ResponseSpecBuilder Class
7.1.
Using ResponseSpecBuilder
7.2.
Implementation in Java
7.2.1.
Output
8.
Frequently Asked Questions
8.1.
What is REST Assured?
8.2.
What is the use of REST Assured?
8.3.
Which is better, postman or rest assured?
8.4.
What is ResponseSpecBuilder?
8.5.
What is the need for ResponseSpecification?
9.
Conclusion
Last Updated: Mar 27, 2024
Medium

Specify How The Expected Response Must Look Like In REST Assured

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Hey Ninja! Are you learning API testing? If your answer to that question was yes, you must be familiar with the API (Application Programming Interface) testing tools. We will talk about one such tool, which is REST assured. In previous blogs, you must’ve read about how to set, retrieve and assert Content-Type for request in Rest Assured. In this article, we will see what the expected Response should look like in REST assured. 

how the expected response must look like in rest assured

REST (Representational State Transfer) is an architectural paradigm for defining requirements for web services. Let us now go over REST assured in greater detail.

REST Assured

The REST Assured is an open-source library based on Java. It is used for testing REST web services. It integrates well with Maven. It enables us to develop readable, maintainable, and resilient Java tests for RESTful APIs. REST Assured tests execute on existing unit testing frameworks such as TestNG or JUnit.

Rest Assured allows the user to specify the expected values for each element in the API request and will automatically verify that the actual Response matches the expected values. That ensures that the API is functioning correctly and providing the expected results.

All REST methods, including GET, PUT, POST, PATCH, and DELETE, are supported by REST Assured.

Let us now find out the advantages of using REST assured.

Advantages of REST Assured

Some of the advantages of REST Assured are as follows:

  • No need to worry about licensing because it's an open-source tool.
     
  • It is compatible with all HTTP methods.
     
  • It includes a JSON schema validation library for validating JSON schema.
     
  • It supports various API authentication schemes.
     
  • REST Assured makes it simple to parse and validate XML and JSON.
     
  • As a test framework, you can use REST Assured with other Java frameworks like TestNG and Junit.
     

Let us move forward to the disadvantages of REST Assured.

Disadvantages of REST Assured

A few drawbacks of REST Assured are listed below:

  • It is not purely thread-safe.
     
  • You need to have sound knowledge of Java to use REST Assured.
     
  • REST Assured does not explicitly support SOAP APIs.
     

Now let us learn how the expected Response must look in REST Assured.

Expected Response in Rest Assured

When using Rest Assured, the expected Response must include the following elements:

  • The HTTP status code is the numerical value indicating the Response's status, such as 200 for success or 404 for not found.
     
  • The Response body is the actual content of the Response, such as JSON or XML payload containing the data returned by the API.
     
  • The Response headers are the additional metadata included in the Response, such as the content type and length of the Response body.
     
  • The Response time is the time the server took to process and return the Response.

How The Expected Response is Defined

definition of expected response includes

In Rest Assured, we define the expected Response using a combination of the following methods:

statusCode(int code): We use it to specify the needed HTTP status code in the Response.

contentType(ContentType contentType): to specify the expected content type in the Response, such as JSON or XML.

body(String pattern, Object... arguments): to specify the expected Response body, using a regular expression or string pattern to match the Response.

For example, if you are expecting a JSON Response with a status code of 200, you could use the following syntax:

Syntax

given()
  .when()
    .get("/some/endpoint")
  .then()
    .statusCode(200)
    .contentType(ContentType.JSON)
    .body("key1", "value1")
    .body("key2", "value2")

Explanation

We have used the given(), when(), and then() methods to define the request and expected Response. We use the status code () and contentType () methods to specify the desired HTTP status code and content type (). We use the body() method to set the expected values in the Response body. The Response variable will contain the Response from the API. The then() call is used to validate the Response.

Remember that this is just one example of defining the expected Response in Rest Assured. You can use many methods to specify the expected Response. It depends on your specific needs.

Now that we know what the expected Response is, let us move on to the ResponseSpecification. 

ResponseSpecification in REST Assured

In practice, we may need to write many tests. A group of tests will share similar assertions on the Response. If we need to make changes, we must do so at every point where we have used these assertions. That will be a time-consuming process and is thus not recommended. 

The ResponseSpecification feature in Rest Assured allows us to group common assertions and present them as a single entity. An interface called ResponseSpecification enables you to define the expected Response requirements for a test to pass. This interface provides methods for defining assertions such as content type, status code, etc. To obtain a reference for the ResponseSpecification, we must use the RestAssured class's expect() method. We cannot create an object of ResponseSpecification because it is an interface.

Need for RequestSpecification in REST Assured

Consider the following example of one such case where we have common assertions.

In this example, we used the public API of “https://restful-booker.herokuapp.com” for testing. You'll notice that the assertions for Responses in the methods getBookingsWithoutResponseSpec() and invalidNameWithoutResponseSpec() had to be repeated.

Implementation in Java

package tests;
import org.hamcrest.Matchers;
import org.testng.annotations.Test;
 
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
public class Testeg {
	@Test
	public void getBookingsWithoutResponseSpec()
	{

		RestAssured

		// Given method.
 		 .given()
 		.baseUri("https://restful-booker.herokuapp.com")
 
		// When method.
 		 .when()
 		 .get("/booking")
  
		// Then method.
 		 .then()
  
		// Response.
		 .contentType(ContentType.JSON)
		 .time(Matchers.lessThan(5000L))
		 .statusLine("HTTP/1.1 200 OK")
  
		// Verifying the count of bookings.
		 .body("size()", Matchers.greaterThan(5)); 
	}

	@Test
	public void invalidNameWithoutResponseSpec()
	{

		// Given method.
		RestAssured
	  	.given()
 		.baseUri("https://restful-booker.herokuapp.com")
 
		// When method.
  		.when()
  		.get("/booking?firstname=Gaurangi")
  
		// Then method.
  		.then()
  
		// Repetition of Response.
  		.contentType(ContentType.JSON)
  		.time(Matchers.lessThan(5000L))
  		.statusLine("HTTP/1.1 200 OK")
  
		// Verifying the number of bookings.
  		.body("size()", Matchers.equalTo(0));

	}
}

Output 

output without responsespecification

This test works fine without any errors. However, repetition of common assertions takes time and effort. With the help of RequestSpecifaction in REST Assured, we can club these common assertions together. 

Let us now look at an example of how to use ResponseSpecification in REST Assured.

Using ResponseSpecification

To use ResponseSpecification in REST Assured, firstly, you have to create a ResponseSpecification. Then, you can add it using the spec() method. Consider the example that follows to understand it better.

In this example, We used a public API of “https://restful-booker.herokuapp.com” for testing. We created a ResponseSpecification named respSpec and used it in functions “getBooking()” and “invalidName().” Notice how this allowed us to avoid the repetition of common assertions. 

Implementation in Java

package tests;

import org.hamcrest.Matchers;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.specification.ResponseSpecification;

public class Testeg {
	ResponseSpecification respSpec = null;

	@BeforeClass
	public void setRespSpec()
	{
		// Creating a ResponseSpecification in REST Assured.
		respSpec=  RestAssured.expect();
		respSpec.contentType(ContentType.JSON);
		respSpec.statusCode(200);
		respSpec.time(Matchers.lessThan(5000L));
		respSpec.statusLine("HTTP/1.1 200 OK");

	}

	@Test
	public void getBookings()
	{

		// Given method
		RestAssured
  		.given()
		.baseUri("https://restful-booker.herokuapp.com")

		// When method
  		.when()
  		.get("/booking")

		// Then method
  		.then()
  
  		// passing the created Response specification
  		.spec(respSpec)

		// Verifying booking count
  		.body("size()", Matchers.greaterThan(5));

	}

	@Test
	public void invalidName()
	{

		// Given method
		RestAssured
  		.given()
		.baseUri("https://restful-booker.herokuapp.com")

		// When method
  		.when()
  		.get("/booking?firstname=Gaurangi")

		// Then method
  		.then()


        // Passing created ResponseSpecification
  		.spec(respSpec)

		// verifying count of bookings
 		 .body("size()", Matchers.equalTo(0));

	}
}

Output

output with responsespecification

We can also create a ResponseSpecification in REST Assured using the ResponseSpecBuilder class. Let us learn more about the ResponseSpecBuilder class.

ResponseSpecBuilder Class

As the name implies, this class gives us a builder to create ResponseSpecifications. In contrast to the methods of the ResponseSpecification interface, this class has self-explanatory methods like expectStatusCode(), expectHeaders(), etc.

Let's see how we can use this class to make ResponseSpecifications.

Using ResponseSpecBuilder

Look at the example that follows to understand how we use the ResponseSpecBuilder class.

Implementation in Java

package tests;

import org.hamcrest.Matchers;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.ResponseSpecification;

public class Testeg {
	ResponseSpecification respSpec = null;

	@BeforeClass
	public void setRespSpec()
	{
		// Using ResponseSpecBuilder to ResponseSpecifications.
		respSpec = new ResponseSpecBuilder()
		.expectStatusCode(200)
   		.expectStatusLine("HTTP/1.1 200 OK")
    	.expectContentType(ContentType.JSON)
   		.expectResponseTime(Matchers.lessThan(5000L)) 
   		.build();
	}

	@Test
	public void getBookingsWithResponseSpecBuilder()
	{

		// Given method.
		RestAssured
 		.given()
		.baseUri("https://restful-booker.herokuapp.com")
 
		// When method.
  		.when()
  		.get("/booking")
  
		// Then method.
  		.then()
  
   		// Passing ResponseSpecification.
  		.spec(respSpec)
  
		// To verify booking count.
  		.body("size()", Matchers.greaterThan(5));

	}

	@Test
	public void invalidFirstNameWithResponseSpecBuilder()
	{

		// Given method.
		RestAssured
  		.given()
		.baseUri("https://restful-booker.herokuapp.com")
 
		// When method.
  		.when()
  		.get("/booking?firstname=Gaurangi")
  
		// Then method.
  		.then()
  
		// Passing ResponseSpecification.
  		.spec(respSpec)
  
		// Verifying the number of bookings.
  		.body("size()", Matchers.equalTo(0));

	}
}

Output

output with responsespecbuilder

Now that we know how the expected Response must look in REST Assured, let us address some FAQs.

Frequently Asked Questions

What is REST Assured?

REST Assured is a Java library that delivers a domain-specific language (DSL) to write robust, maintainable tests for RESTful APIs.

What is the use of REST Assured?

It removes the need to write a lot of code required for setting up an HTTP connection, sending a request, and receiving and parsing a Response.

Which is better, postman or rest assured?

Rest assured is better than the postman. Rest assured, you can reuse code as it is a Java client. Moreover, in postman, we can provide only one data file for each collection, unlike rest assured.

What is ResponseSpecBuilder?

As the name implies, it is a class that provides us with a builder to create ResponseSpecifications. 

What is the need for ResponseSpecification?

We can use the ResponseSpecification feature in Rest Assured to group common assertions and present them as a single entity.

Conclusion

In this article, we learned about the expected Response in REST Assured. We also learned about the ResponseSpecification interface and the ResponseSpecBuilder class.

To learn more about REST assured, refer to

Please refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. And also, enroll in our courses and refer to the mock test and problems available. Have a look at the interview experiences and interview bundle for placement preparations.

Happy Learning!

Live masterclass