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

Graphic with a blue background featuring hexagonal icons and digital symbols, titled 'API Test Automation Using Rest Assured.' The image includes an icon representing API connectivity in the top left and the Codoid logo in the bottom right corner

Rest Assured is a useful library in Java. It is designed for testing RESTful web services. It simplifies sending HTTP requests and receiving responses. This helps QA workers see how APIs perform. This guide covers the key steps for automating API tests using Rest Assured.

Why Use Rest Assured for API Testing?

Rest-Assured works like a client without a user interface. It allows you to send flexible HTTP requests. You can also look at the responses from a RESTful server. It supports all the HTTP methods: GET, POST, PUT, DELETE, and PATCH. This makes it useful for API testing.

You can look at important parts of the HTTP response, like:
  • Status Codes (such as 200, 404, 500)
  • Response Body (like JSON, XML, and more)
  • Headers
  • Response Time

Rest Assured is popular because it works well with Java. It is simple to use and gives clear reports.

BDD Approach in Rest Assured

Rest Assured uses a method called Behavior-Driven Development (BDD). This method helps make tests simpler to read and understand. Testers can clearly describe how the API works by using the terms given(), when(), and then().

  • given(): Shows input details like Base URI, Headers, Path, or Request Parameters and Request Body.
  • when(): States the resource and the HTTP method (GET, POST, PUT, PATCH, DELETE).
  • then(): Confirms the response by checking the status code, response body, headers, and response time.

Pre-requisites

  • Java JDK (8 or higher): Familiarity with Java is essential as Rest Assured is a Java-based library.
  • Maven or Gradle: Use Maven or Gradle as build tools to manage dependencies.
  • IDE: Use an IDE like IntelliJ IDEA or Eclipse to write and execute your test scripts.
  • Testing Framework: Rest Assured works well with TestNG or JUnit for assertions and test management.
  • Basic knowledge of Java and understanding of REST APIs.

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