What is Rest Assured?

Rest Assured enables you to test REST APIs using java libraries and integrates well with Maven. It has very efficient matching techniques, so asserting your expected results is also pretty straight forward. Rest Assured has methods to fetch data from almost every part of the request and response no matter how complex the JSON structures are.

For the testing community, API Automation Testing is still new and niche. The JSON complexities keep API testing unexplored. But that does not make it less important in the testing process. Rest Assured.io framework has made it very simple using core java basics, making it a very desirable thing to learn.

In this tutorial, you will learn,

Why need Rest-Assured?

Imagine you open your google map view and look for a place you want to go, you immediately see closeby restaurants, you see options for the commute; from some leading travel providers, and see so many options at your fingertips. We all know they are not google products, then how does Google manage to show it. They use the exposed APIs of these providers. Now, if you are asked to test this kind of setup, even before the UI is built or is under development, testing APIs becomes extremely important and testing them repeatedly, with different data combinations makes it a very suitable case for automation.

Earlier, we were using dynamic languages such as groovy, ruby to achieve this, and it was challenging. Hence API testing was not explored by functional testing.

But using Rest Assured, automation testing of APIs, sending simple https requests with user-friendly customizations is simple if one has a basic background of java. It is needed to understand API testing, and integration testing, but post that automation Rest Assured gives very good confidence on the backend while front-end testing can just focus on the UI and client-side operations. Rest Assured is a open source with a lot of additional methods and libraries being added has made it a great choice for API automation.

Step by step guide for the setup of Rest Assured.io

Step 1) Install Java. Refer to this guide

Step 2) Download an IDE to begin: eclipse

Step 3) InstallMaven and set up your eclipse. Refer here.

Setup Rest Assured

  1. Create a Maven Project in your IDE. We are using Intellij, but you will get a similar structure on any IDE you may be using.
  2. Open your POM.xml
Project structure

For Rest Assured.io: For Java version < 9 users:

Add the below dependency to your POM.xml:

<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>4.2.0</version>
<scope>test</scope>
</dependency>


<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>xml-path</artifactId>
<version>4.2.0</version>
<scope>test</scope>
</dependency>


<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>4.2.0</version>
<scope>test</scope>
</dependency>

For Rest Assured.io : For Java version 9+ users :

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

Troubleshooting:

In case you see errors and not sure if the dependencies got downloaded well,

  1. Perform a maven build to import all dependencies, again you will find help on Maven set up on guru99.
  2. Still, you see errors, then do a maven clean followed by a maven install, and it should build without any errors.
  3. You can add the below lines in your java class and see no compile errors are present.
import io.restassured.RestAssured.*;
import io.restassured.matcher.RestAssuredMatchers.*;
import org.hamcrest.Matchers.*;
        

First simple Rest Assured script

Syntax:

The syntax of Rest Assured.io is the most beautiful part, as it is very BDD like and understandable.

Given(). 
        param("x", "y"). 
        header("z", "w").
when().
Method().
Then(). 
        statusCode(XXX).
        body("x, ”y", equalTo("z"));

Explanation:

Code Explanation
Given() 'Given' keyword, lets you set a background, here, you pass the request headers, query and path param, body, cookies. This is optional if these items are not needed in the request
When() 'when' keyword marks the premise of your scenario. For example, 'when' you get/post/put something, do something else.
Method() Substitute this with any of the CRUD operations(get/post/put/delete)
Then() Your assert and matcher conditions go here

Now that you have the setup and some background to the syntax, let's create our first simple test. It is okay if so far the structure seems new to you, as you code further interpret each line, you will get the hang of it.

What will you fetch?

Open your browser and hit - http://demo.guru99.com/V4/sinkministatement.php?CUSTOMER_ID=68195&PASSWORD=1234!&Account_No=1. Ensure you see something as below.

In case you get an error on the browser when you try to get a response for the request,

  1. See if you have used Https or Http. Your browser might have settings to not open insecure websites.
  2. See if you have any proxy or firewall blocks your browser from opening websites.

*Note – you did not use any headers here, no body, and no cookie. It was a URL and also you are getting content from the API and not posting or updating any existing content, so that makes it a GET call. Remember this to understand our first test better.

The Objective of your test:

The goal of the script is to print the same output on your IDE console as what you received on the browser through Rest Assured.

Let us code this with the below steps:

Getting the response Body

Step 1) Create a class named as "myFirstRestAssuredClass"

Step 2) Create a method called "getResponseBody"

Step 3) Similar to the structure learned earlier of given, when and then, type the below code

given(). -> No headers required, no query or path param.

when(). -> No specific condition setup

get('http://demo.guru99.com/V4/sinkministatement.php?CUSTOMER_ID=68195&PASSWORD=1234!&Account_No=1'). ->only the url needs to be supplied

then(). -> No specific assertions required

log(). all() -> Once all the response is fetched, log response, headers, essentially everything that the request returns to you.

public static void getResponseBody(){
   given().when().get("http://demo.guru99.com/V4/sinkministatement.php?CUSTOMER_ID=68195&PASSWORD=1234!&Account_No=1").then().log()
  .all();
 
}

Now notice that the URL used is long and less readable, if you look closely, you will notice that 3 query parameters are being used which are

  1. Customer_ID
  2. Password
  3. Account_No

Rest Assured, helps us pass every part(query, path, header param) separately, making the code more readable and easy to maintain. Also, we can parameterize the data from an external file as required.

For using query param, we go back to our definition of the syntax and see that all of them are passed as a part of given.

public static void getResponseBody(){
 
   given().queryParam("CUSTOMER_ID","68195")
           .queryParam("PASSWORD","1234!")
           .queryParam("Account_No","1")
           .when().get("http://demo.guru99.com/V4/sinkministatement.php").then().log()
           .body();
}

**Note that we used "body" instead of "all"; this helps us to extract only the body of the response.

Output:

Output for getResponseBody

Getting the response status code

The next method that we script will be to get the status code and also put an assertion to validate the same.

Step 1) Create a method called getResponseStatus()

Step 2) Use the same request structure used above. Copy and paste it.

Step 3) Instead of logging it, we use the 'getStatusCode' inbuilt method of Rest Assured to fetch the status code value

Step 4) In order to assert that your status code is 200, we use the keywords - assertThat().statusCode(expectedCode)

**Note - URL is a variable used for simplicity. URL holds the entire API request URL

public static void getResponseStatus(){
   int statusCode= given().queryParam("CUSTOMER_ID","68195")
           .queryParam("PASSWORD","1234!")
           .queryParam("Account_No","1") .when().get("http://demo.guru99.com/V4/sinkministatement.php").getStatusCode();
   System.out.println("The response status is "+statusCode);

   given().when().get(url).then().assertThat().statusCode(200);
}

Output:

Output for getResponseStatus

Business need

One of the basic rules of automation is that we have to put checkpoints so that the test proceeds only if all the required conditions are met. In API testing, the most basic validation is to check if the status code of the request is in 2XX format.

The complete code, so far:

import java.util.ArrayList;
import static io.restassured.RestAssured.*;
import static java.util.concurrent.TimeUnit.MILLISECONDS;

public class myFirstRestAssuredClass {

   final static String url="http://demo.guru99.com/V4/sinkministatement.php?CUSTOMER_ID=68195&PASSWORD=1234!&Account_No=1";

   public static void main(String args[]) {

     getResponseBody();
     getResponseStatus();

; }

   //This will fetch the response body as is and log it. given and when are optional here
   public static void getResponseBody(){
       given().when().get(url).then().log()
      .all();

  given().queryParam("CUSTOMER_ID","68195")
               .queryParam("PASSWORD","1234!")
               .queryParam("Account_No","1") .when().get("http://demo.guru99.com/V4/sinkministatement.php").then().log().body();
   }

public static void getResponseStatus(){
   int statusCode= given().queryParam("CUSTOMER_ID","68195")
           .queryParam("PASSWORD","1234!")
           .queryParam("Account_No","1")
           .when().get("http://demo.guru99.com/V4/sinkministatement.php").getStatusCode();
   System.out.println("The response status is "+statusCode);

   given().when().get(url).then().assertThat().statusCode(200);
}

}

*Note:

  1. 200 is a successful response for this scenario. At times, you need the request to fail as well, and then you might use 4XX or 5XX. Do try to change the status code by supplying invalid parameters and check.
  2. When we assert a condition, there will be no printing on the console unless there is an error.

Script to fetch different parts of a response

Fetching response body and response status code is already covered in the above segment. It is worthy to note that to fetch different parts of the response, the keyword 'extract' is very important.

Header

Rest Assured is a very straightforward language, and fetching headers is just as simple. The method name is headers(). Like before, we will create a standalone method to do the same.

public static void getResponseHeaders(){
   System.out.println("The headers in the response "+
                   get(url).then().extract()
           .headers());
}

Please note that 'given().when()' is skipped here, and the code line starts from get(), this is because there is no precondition or verification made here to hit the request and get a response. In such cases, it's optional to use the same.

Output :

Output for getResponseHeader

Business need:

Quite a few times, you would need to use the authorization token, or a session cookie for the subsequent request, and mostly, these details are returned as headers of the response.

Response Time

To get the time needed to fetch the response from the backend or other downstream systems, Rest Assured provides a method called 'timeIn' with a suitable timeUnit to get the time taken to return the response.

public static void getResponseTime(){
  System.out.println("The time taken to fetch the response "+get(url)
         .timeIn(TimeUnit.MILLISECONDS) + " milliseconds");
}

Output:

Output for getResponseTime

Business need:

A very important feature of testing APIs is their response time, to measure the performance of the application. Note that the time taken for your call may take more or less time depending on your internet speed, the performance of the API at that time, server load, and other factors impacting the time.

Content-Type

You can get the content-Type of the response returned using the method is "contentType ()".

public static void getResponseContentType(){
   System.out.println("The content type of response "+
           get(url).then().extract()
              .contentType());
}

Output

Output for getContentType

Business Need:

At times getting the content-type is essential for ensuring there are no security gaps for any cross-origin threats or just to ensure the content passed is as per the standards of the API.

Fetch Individual JSON Element

From the given response, you are asked to calculate the total amount, you need to fetch every amount and sum it up.

Steps:

Step 1) The amount field is within an array with Key "statements" which is in turn in the list with key "result"

Step 2) Rest Assured, provides a mechanism to reach the values in the API using "path"

Step 3) The path to reach amounts is "result.statements.AMOUNT". Think of it like Xpath in selenium.

Step 4) Fetch all amounts in a collection, and then loop for all values to calculate the sum

public static void getSpecificPartOfResponseBody(){

ArrayList<String> amounts = when().get(url).then().extract().path("result.statements.AMOUNT") ;
int sumOfAll=0;
for(String a:amounts){

    System.out.println("The amount value fetched is "+a);
    sumOfAll=sumOfAll+Integer.valueOf(a);
}
System.out.println("The total amount is "+sumOfAll);

}

Note: Since the amount value is in string data type, we convert to integer and use it for summation.

Output:

Output for getSpecificPartOfResponse

Summary:

  • Rest Assured is a group of java libraries which enables us to automate Rest API testing
  • Rest Assured is Java-based, and knowledge of core Java suffices for learning it
  • It helps fetch values of request and response from complicated JSON structures
  • The API request can be customized with a variety of header, query, path param, and any session or cookies to be set.
  • It helps set assert statements and conditions.
  • While Rest Assured is very helpful when the response is JSON type, it's methods may not work seamlessly if content type id HTML or plain text.

 

YOU MIGHT LIKE: