In this tutorial, you will learn,

What is Rest Assured? Why need Rest-Assured?
Step by step guide for the setup of Rest Assured.io
First simple Rest Assured script
Script to fetch different parts of a response

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. 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

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. Open your POM.xml

For Rest Assured.io: For Java version < 9 users: Add the below dependency to your POM.xml: For Rest Assured.io : For Java version 9+ users :

Troubleshooting:

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

Perform a maven build to import all dependencies, again you will find help on Maven set up on guru99. Still, you see errors, then do a maven clean followed by a maven install, and it should build without any errors. You can add the below lines in your java class and see no compile errors are present.

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.

Explanation:

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,

See if you have used Https or Http. Your browser might have settings to not open insecure websites. 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. 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

Customer_ID Password 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. **Note that we used “body” instead of “all”; this helps us to extract only the body of the response. Output:

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 Output:

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: *Note:

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. 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.

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. 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 :

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. Output:

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 ()”. Output

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 Note: Since the amount value is in string data type, we convert to integer and use it for summation. Output:

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.