Select Page
API Testing

How to Perform API Test Automation using Rest Assured?

Find out everything you will need to know to achieve API Test Automation using Rest Assured. Example Program included for easy understanding

How to Perform API Test Automation using Rest Assured - Blog
Listen to this blog

To be a complete tester, it is very important for you to know how to perform Automated API testing. It enables you to test the business logic of an application early on even before the UI is ready. There are many aspects to API testing, but it generally involves making requests to one or more API endpoints and validating the response for various reasons. And Rest Assured is a great option for API Test Automation as it offers a lot of methods that can be used to fetch data from almost every part of the request or response for our testing. So in this Rest Assured Tutorial, we will be focusing on how to easily achieve API Test Automation using Rest Assured. We have also included a sample program to make it easier for you to understand the core concepts.

What is Rest Assured?

Rest-Assured is a Java-based library for testing RESTful Web Services. Accessing REST web services can be made easier by using this library, which behaves like a headless client.

As stated earlier, it is possible to create highly customizable HTTP requests to send to a Restful server. So you can use Rest Assured to send a wide range of request combinations to test the different combinations of the core business logic.

You can also use Rest Assured to validate HTTP responses received from the server. For example, we can verify the Status code, Status message, Headers, and Body of the response.

How to Perform API Test Automation using Rest Assured?

Create a Maven Project

The first of the two prerequisite steps to start API Test automation with Rest assured would be to create a Maven project by following the specified steps

File->New-> Project -> Maven Archetype -> Project_Name -> Create

Creating Maven Report on API Test Automation using Rest Assured

Add the Rest Assured dependency to your POM file

Now that you have created your Maven project, you must add the below-specified dependency to your POM.xml file.

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

Make a detailed HTTP request

The next step in performing API test automation using Rest Assured is to create a detailed HTTP request URI that contains the unique address of the request.

Components of an HTTP Request

URI:

The URI is composed of the Base, Resource, Query, and Path.

Uri Components Of Http Request

Header:

An HTTP header is a meta-data attached to a request or response. So it is additional information sent with a request or response between a client and a server to serve a particular purpose such as authentication, caching, or sending messages.

Body:

Users send information to the server via the body which can be in the Payload, String, or File format.

Commands:

With the REST interface, the four basic operations are crucial to achieve API Test Automation using Rest Assured. The 4 basic operations Create, Read, Update, and Delete (CRUD) are performed via the POST, GET, and PUT methods.

GET: To retrieve or read the server’s data.

POST: It is used to add a resource to the server.

PUT: To update an existing record completely.

PATCH: If only a partial update has to be made to an existing record.

DELETE: Deletes a resource from a server.

Send the request over the network

You will be able to send the payload to the request body using a String or a JSON object. You can also send the JSON file as the payload to the request body.

Verifying the received Response

Based on the response code you receive, you will be able to identify the status of the request. There are several status codes that you’ll have to know, but we have listed the most important ones below.

200 – When the request is a success

201 – Request succeeded and has created the resource

400 – Server couldn’t process the request due to a client error

429 – When someone has sent too many requests

404 – When the requested page is not available

Example Program:

In this example for API Test Automation using Rest Assured, we will be adding an employee’s details to the server and verifying if the data was updated correctly.

package cap.utilities;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class APIUtil {
   private static Map<String, Set<?>> dataMapForTestCaseDetails = new HashMap<>();
   public static void main(String[] args) throws JsonProcessingException {
       try {
           RestAssured.baseURI = "https://reqres.in/";
           String strURITokenForPost = "api/users";
           RequestSpecification request = RestAssured.given();
           JSONObject requestParams = new JSONObject();// JSON Object Creation
           requestParams.put("name", "John"); // Adding the information as key-value pair in the JSON
           requestParams.put("job", "tester");
           request.body(requestParams);
           request.header("Content-Type", "application/json");
           Response response = request.post(strURITokenForPost); // here we are hitting the uri
           System.out.println("\n Status Code: " + response.getStatusCode()); // Response status code is printed here 
           System.out.println("---> Response JSON Body: " + response.getBody().asString());
       } catch (
               Exception ex) {
           System.out.println("WARNING: " + ex.getMessage() + " In API Util class file.");
       }
   }
}
Output

Output of Verified Received Response

Code Explanation:

To make it even easier, we have explained the important parts of the sample code we have mentioned to perform API Test Automation using Rest Assured.

  • Though we can add other details such as authentication, caching, and so on, we have mentioned only the content type in the header part.
  • We have mentioned our base URI, base path, and given() to get the reference of the request specification
  • We have created a JSON object and added the information (Name & Job) in the key-value pair and passed it into the body.
  • Next, the request is hit with a post command which is used to add information to the server.
  • Finally, we got the status code as 201 as the script passed. If the script had failed, it would have thrown an exception.

Conclusion

We hope you are now clear on how to perform API Test Automation using Rest Assured. Being a leading API Testing Services company, we have used various other tools such as SoapUI, Postman, and so on. We have also written numerous in-depth blogs about API testing as well. So make sure to go through our entire collection and subscribe to our newsletter to not miss out on any of our latest blogs.

Comments(0)

Submit a Comment

Your email address will not be published. Required fields are marked *

Talk to our Experts

Amazing clients who
trust us


poloatto
ABB
polaris
ooredo
stryker
mobility