REST Assured Tutorial: How to test API with Example

You are able to test REST APIs with Rest Assured by making use of Java libraries, and it interacts quite well with Maven. Because it employs very effective matching algorithms, determining whether or not it has produced the outcomes you anticipated is a rather simple matter. No matter how complicated the JSON structures are, Rest Assured includes methods that can retrieve data from virtually every aspect of both the request and the response.

API Automation Testing is still relatively novel and specialised within the testing community. Because of all the intricacies of JSON, API testing is rarely done. However, this does not in any way diminish its significance in the evaluation process. Relax and be at ease. Because the io framework has made using the fundamentals of core Java so much easier, learning it has become something that many people are interested in doing.

Why need Rest-Assured?

Imagine you open up Google Map View and seek for a destination you want to go. Immediately, you see alternatives for the commute; from some of the biggest travel providers, and you have so many options right at your fingers. This is exactly what would happen. If everyone is aware that they are not Google products, one would wonder how Google can still show them. They make advantage of the public APIs made available by these suppliers. When you are asked to test this kind of setup, even before the UI is built or is in the process of being developed, testing APIs becomes extremely important, and testing them repeatedly, with different data combinations, makes it a very suitable case for automation. Now, if you are asked to test this kind of setup, even before the UI is built or is in the process of being developed, testing APIs becomes extremely important

In the past, we attempted to accomplish this using dynamic programming languages such as Groovy and Ruby, which was a difficult task. Therefore, testing of the API was not included in the functional testing.
It is not difficult to utilise Rest Assured, an automation testing tool for APIs, to send straightforward HTTP queries that may be customised in a way that is user-friendly if one has a fundamental understanding of Java. It is necessary to have an understanding of API testing and integration testing; however, if that automation has been completed, Rest Assured provides very good confidence in the backend, allowing front-end testing to concentrate solely on the UI and client-side processes. The fact that Rest Assured is an open source project that continually has new features, including methods and libraries, added to it makes it an excellent option for API automation.

Step by step guide for the setup of Rest

Instructional walkthrough for the installation of Rest
Step 1) Install Java. Please consult this user guide.

Step 2) To get started, you will need to download an IDE: eclipse

Installing Maven and configuring Eclipse is the third step. Refer here.

The Stage Is Set, Be At Ease
Make sure that your IDE has a Maven Project created. Although we use Intellij, the structure that you will see in any integrated development environment (IDE) will be very similar.
Open your POM.xml

The following describes the project structure for Rest Users using Java versions lower than 9:

Include the dependency described below in your POM.xml file:

<dependency> \s<groupId></groupId> \s<artifactId>

json-path</artifactId> \s<version>4.2.0</version> \s<scope>test</scope> \s</dependency>

<dependency> \s<groupId></groupId> \s<artifactId>xml-path</artifactId> \s<version>4.2.0</version> \s<scope>test</scope> \s</dependency>

<dependency> \s<groupId></groupId> \s<artifactId>

json-schema-validator</artifactId> \s<version>4.2.0</version> \s<scope>test</scope> \s</dependency>
Users of Java versions 9 and higher who have Rest

<dependency> \s<groupId></groupId> \s<artifactId>rest-assured-all</artifactId> \s<version>4.2.0</version> \s<scope>test</scope> \s</dependency>
In the event that you notice issues and are unsure as to whether or not the dependencies were downloaded correctly

First simple Rest Assured script

Execute a maven build in order to import all of the dependencies; once again, assistance with setting up Maven may be found on guru99.
In the event that you continue to see errors, perform a maven clean followed by a maven install, and the project should build without displaying any error messages.
You can add the lines below to your Java class, and you will see that there are no build problems present.
First simple Rest Assured script. import io.restassured.RestAssured.*, import io.restassured.matcher.RestAssuredMatchers.*, and import org.hamcrest.Matchers.*.
Because it is very similar to BDD and easy to comprehend, the syntax of Rest is one of its most attractive features.

Given(). param (“x”, “y”).
the header (“z”, “w”).
body(“x, “y”, equalTo(“z”));
In the event that the browser throws an error while you are attempting to acquire a response to the request, the following instructions will help.

Check to see if you have utilised the HTTP or HTTPS protocol. It’s possible that your browser has settings that prevent it from opening potentially dangerous websites.
Check to see if there is a proxy or a firewall that is preventing websites from opening in your browser.
Please take note that you have not included any headers, any content, or any cookies in this message. Because it was a URL and because you are retrieving stuff from the API rather than submitting new content or modifying any that already exists, the call was classified as a GET call. Keep this in mind so that you can perform better on our first test.

The following is the goal of your examination:
The purpose of the script is to print the identical output on your IDE console as what you obtained using Rest Assured in the browser.

In order to code this, let us follow these steps:
Achieving the desired response Body
1) Begin by generating a new class and giving it the name “myFirstRestAssuredClass.”

Step 2: Develop a procedure that will be known as “getResponseBody.”

Step 3: Type in the following code using a format similar to the one learned previously, which consists of the words supplied, when, and then.

provided() means that no headers are necessary, and that there are no query or path parameters.

when(). -> There is not a predetermined condition setup.


(‘ ID=68195&PASSWORD=1234!&Account No=1‘). ->the only piece of information required is the URL.

then() -> There is no need for any specific assertions.

log(). all() -> Once all of the answer has been retrieved, you should log it along with the headers and basically everything else that the request sends back to you.

public static void getResponseBody(){ provided (). when(). get(“ ID=68195&PASSWORD=1234!&Account No=1”). then(). log() . all();

Observe now that the URL that was used is quite lengthy, making it less easy to understand; if you examine it more carefully, you’ll see that it makes use of three query parameters, which are as follows:

Customer ID \sPassword \sAccount No \sRest Assured, enables us pass every part (query, path, header param) independently, which makes the code easier to comprehend and maintain overall. In addition, the data that comes from an external file can be parameterized according to the requirements.

In order to use the query param, we must first refer back to our earlier explanation of the syntax and note that each of these components is included in the provided.

getResponseBody() is a public static void function.


queryParam(“CUSTOMER ID”,”68195″) .

queryParam(“PASSWORD”,”1234!”) .

queryParam(“Account No”,”1″) .



then().log() is everything you need.

body(); Please take note that we chose to use “body” rather than “all”; this allows us to extract just the body of the response from the page.


Output for getResponseBody
Obtaining the status code for the response
The next step that we will script is to retrieve the status code and also to put an assertion in place to validate it.

1) Develop a procedure that will be known as getResponseStatus ()

Step 2: Make use of the same format for the request that was utilised in Step 1. Make sure you copy and paste it.

Step 3: To retrieve the status code value, rather than recording it, we make use of the ‘getStatusCode’ inherent function that is included with Rest Assured.

Step 4: Utilizing the keywords assertThat allows us to verify that the current status of your connection is 200. ().


**Note: URL is a variable that is utilised because it is simpler. The request URL contains the entirety of the API request URL.

public static void getResponseStatus(){ int statusCode= provided (). queryParam(“CUSTOMER ID”,”68195″) . queryParam(“PASSWORD”,”1234!”) . queryParam(“Account No”,”1″) . when(). get(“”). getStatusCode(); System.out. println(“The response status is “+statusCode);




then().assertThat().statusCode(200); \s} \sOutput:

The output serves the business needs of getResponseStatus

When it comes to automation, one of the most fundamental laws is that we have to set up checkpoints so that the test will only continue if all of the necessary requirements are satisfied. When performing API testing, the most fundamental validation is determining whether or not the request’s status code is in the 2XX format.

The entire code, up to this point:

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

general population myFirstRestAssuredClass ===================

final static String url=” ID=68195&PASSWORD=1234!&Account No=1″; final static String url=””;

public static void main (String args[]) {

getResponseBody(); getResponseStatus();

; }

It will retrieve the response body in its current state and log it. supplied and when are not required in this instance.
given public static void getResponseBody() as the callback function ().
the expression then().log().all();


queryParam(“CUSTOMER ID”,”68195″) .

queryParam(“PASSWORD”,”1234!”) .

queryParam(“Account No”,”1″) .





body(); }

public static void getResponseStatus(){ int statusCode= provided (). queryParam(“CUSTOMER ID”,”68195″) . queryParam(“PASSWORD”,”1234!”) . queryParam(“Account No”,”1″) . when(). get(“”). getStatusCode(); System.out. println(“The response status is “+statusCode);




then().assertThat().statusCode(200); \s}

} \s*Note:

A answer of 200 indicates that this scenario was successfully completed. You might require the request to fail as well at times, in which case you might use the 4XX or 5XX switch. You should check the status code after attempting to change it by providing improper parameters.
If there isn’t a problem, there won’t be any printing done on the console when we assert a condition.
Script that will retrieve various components of a response
The preceding section has already gone over the retrieval of the response body as well as the response status code. It is worthy to remark that the term “extract” plays an extremely significant role in order to retrieve distinct parts of the response.

The language known as Header Rest Assured is incredibly simple, and retrieving headers is just as uncomplicated as the language itself. The name of the method is headers (). As we did before, we will develop a method that can be used independently to accomplish the same goal.

public static void getResponseHeaders() System.out.println(“The headers in the response”+”get”); / System.out.println(“The headers in the response”+”get”); / (url). if (then().extract().headers()), then ();
It is important to take note that the ‘given().when()’ function is not called in this section of code; instead, the line of code begins with the get() function. This is due to the fact that there is no precondition or verification being performed in this section in order to hit the request and obtain a response. In situations like these, the use of the same is not required.


getResponseHeader’s Output in Response to a Business Need:

You are going to need to employ the authorization token quite a few times, or a session cookie for the subsequent request, and the majority of the time, these particulars are going to be returned as headers of the response.

Response Time
Rest Assured provides a method named ‘timeIn’ along with a suitable timeUnit to get the time taken to return the response, which can then be used to calculate the amount of time required to retrieve the response from the backend or from other downstream systems.

public static void getResponseTime() prints the amount of time it took to retrieve the response using the given url followed by System.out.println. timeIn(TimeUnit.MILLISECONDS) + ” milliseconds”);

GetResponseTime’s Business Need, Expressed Through Its Output:

The response time of APIs is a highly significant aspect of API testing because it is used to gauge the overall performance of the application. It is important to keep in mind that the time it takes for your call could be longer or shorter than expected depending on the speed of your internet connection, the performance of the API at that moment, the load on the server, and any other factors that affect the duration.

Using the method “contentType (),” you will be able to determine the content-Type of the response that was returned.

public static void getResponseContentType() is equivalent to the following code: System.out.println(“The content type of response “+ get (url). the expression then().extract().contentType());

Get the output you need from getContentType Business Need:

There are occasions when obtaining the content-type is very necessary for ensuring that there are no security holes for any cross-origin threats or simply to confirm that the material that is passed is in accordance with the standards of the API.

Retrieve an Individual Element of JSON
You are tasked with determining the overall amount based on the information provided, which requires you to get all of the amounts and add them together.


1) The amount field is contained within an array with the key “statements,” which is then contained within a list with the key “outcome.”

Step 2: Rest Assured gives you a way to navigate to specific values in an API by making use of the word “path.”

Step 3: The “result.statements.AMOUNT” path is the one that leads to the amounts. Consider it to be similar to Xpath in selenium.

Step 4) Retrieve all of the amounts contained in a collection, and then iteratively compute the total for each value in the collection.

getSpecificPartOfResponseBody() is a public static void function.

when quantities equal an ArrayList of Strings ().



path(“result.statements.AMOUNT”) ; int sumOfAll=0 ; for(String a:amounts)

sumOfAll = sumOfAll + Integer.valueOf(a); System.out.println(“The amount value obtained is “+a); sumOfAll = sumOfAll +
System.out.println(“The total amount is “+sumOfAll); System.out.println();

Note: Because the value of the amount is of the string data type, we must convert it to an integer before doing the summing.