The Talent500 Blog
API Automation With Rest Assured 1

API Automation With Rest Assured

Introduction

API (Application Programming Interface) is a standard interface that allows different software applications to communicate with one another. APIs have grown in popularity in recent years because they provide a simple way to integrate software systems and exchange data. With the increasing complexity of modern software applications, API testing has become critical.

Rest Assured is a popular Java-based testing framework for automating API testing. Rest Assured and how to use it for API automation will be covered in this blog post.

What is Rest Assured?

Rest Assured is a Java-based library for RESTful web service testing. It includes a domain-specific language (DSL) for writing RESTful web service tests. The Rest Assured DSL is simple to use and offers a lot of flexibility and power for API testing. Rest Assured supports a wide range of HTTP methods, including GET, POST, PUT, DELETE, and others. It also supports a variety of authentication methods, including Basic authentication, Digest authentication, OAuth, and others.

Rest Assured works with a variety of testing frameworks, including JUnit, TestNG, and Cucumber. It can also work with other Java-based tools like Maven and Gradle.

Setting up Rest Assured

Before we can use Rest Assured, we must first configure it in our Java project. Rest Assured can be added to our Java project using Maven or Gradle. In this case, Rest Assured will be installed using Maven.

1.Create a new Maven project 

2.Add the following dependencies to your pom.xml file:

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

<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>7.3.0</version>
    <scope>test</scope>
</dependency>

3.After adding the dependencies, create a new test class and add the following imports:

 

import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

4.We are now ready to start using Rest Assured in our test class.

Automate GET request & Validate Status Code

In this example, we will send a GET request to the API and check the status code of the response. We expect the status code to be 200, which indicates that the request was successful.

@Test

        //public is access modifier and void as nothing is returned for getusers()

public void getusers()
 
    {
 
// resp will contain the response from the api get method for /api/users?page=2
 
            Response resp = given()
.when().get(“serverURL/api/users?page=2”);
 
//save the actual status code in integer variable, variable name is actualstatuscode

int actualstatuscode = resp.getStatusCode();
 
//print the status code in the console
System.out.println(resp.getStatusCode());

      //print the response body in console
System.out.println(resp.getBody().asString());
 
//validating actual status code that we got from API response with the expected status code 200
assertEquals(200,actualstatuscode);
 
}

 

Now in the above code,  instead of assertEquals(200,actualstatuscode); we can also make use of then() like below:

 

.then()
        .statusCode(200);

Import below in your package before using the code and add rest assured/testng jar:

import static io.restassured.RestAssured.given;
import static org.testng.Assert.assertEquals;
import org.testng.annotations.Test;
import io.restassured.response.Response;

To create our test, we use the given(), when(), and assertion methods in this code. The given() method constructs the request, the when() method sends it, and the then() method examines the response. The statusCode() method is used to determine the response’s status code.

 

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.
Then() Your assert and matcher conditions go here

 

Validate the response body of a GET request

In this example, we will send a GET request to the API and check the response body. Instead of using then() we will use assertEquals for validation of response body, but then90 can also be used for response body validation.

@Test(description=“Verify status code for GET method-users/2 as 200”)

public static void verifyStatusCodeGET() {

Response resp=given().when().get(“https://reqres.in/api/users”);

System.out.println(resp.path(“total”).toString());

assertEquals(resp.getStatusCode(),200);

assertEquals(resp.path(“total”).toString(),“12”);

}

 

To check the response body, we use the body() method in this code. The JSON path and the expected value are passed to the body() method. In this example, we inspect the JSON path for the first and second blog posts to ensure that the expected values are present.

Automate a POST request with Rest Assured

In this example, we’ll send a POST request to the API and verify that the response contains the data we’re looking for.

Assume we have an API endpoint that allows us to create new users. JSON request bodies with the fields name, email, and password are accepted by the endpoint. The endpoint returns a JSON response containing the newly created user’s id, name, email, and password.

Through the creation of the following test, we can leverage Rest Assured to automate the process of creating a new user. As we have previously used assertEquals() to verify the response body, we can demonstrate the process of validating response bodies using then() in this example.

@Test
public void testCreateUser() {
    String requestBody = “{\”name\”:\”John Doe\”,\”email\”:\”johndoe@example.com\”,\”password\”:\”password123\”}”;

    given()
        .contentType(“application/json”)
        .body(requestBody)
    .when()
        .post(“https://example.com/api/users”)
    .then()
        .statusCode(201)
        .body(“name”, equalTo(“John Doe”))
        .body(“email”, equalTo(“johndoe@example.com”));
}

 

In this code, we first create a string representation of a JSON request body. We then use the given() method to set the request’s content type to application/json and the body() method to set the request body.

The POST request is then sent to the specified endpoint using the when() method. To specify the HTTP method and endpoint URL, we use the post() method.

Finally, we validate the response using the then() method. The statusCode() method is used to ensure that the response status code is 201. (indicating that the request was successful and a new user was created). We also use the body() method to verify that the response body contains the expected user name and email fields.

Similarly you can also explore to automate rest of the API methods like PUT & PATCH

Automate DELETE method with Rest Assured

This is an example of a Rest Assured test that validates the status code for a DELETE request. The test sends a DELETE request to the specified API endpoint and verifies that the response status code is 204 (indicating that the user was successfully deleted).

Here’s a rephrased version of the code with comments explaining each step:

@Test(description=“Verify 204 status code for deleting a user”, groups= {“RegressionSuite”,“B_User”})
public void testDeleteUser() {
    // Send DELETE request to delete a user
    Response response = given()
        .delete(“https://reqres.in/api/users/2”);

    // Verify that the response status code is 204
    assertEquals(response.getStatusCode(), 204);

    // Print message indicating the test passed
    System.out.println(“Test passed: User deleted successfully with status code 204”);
}

 

In this code, we use the given() method to set up the DELETE request and specify the API endpoint to delete a user. We then use the delete() method to specify the HTTP method and endpoint URL.

We send the request using given().delete() and store the response in the response variable. We then use the assertEquals() method to verify that the response status code is 204.

Conclusion

Rest Assured is a powerful API automation tool. It provides a simple and easy-to-use DSL for writing RESTful web service tests. Rest Assured is compatible with a wide range of HTTP methods, authentication schemes, and testing frameworks. We discussed Rest Assured and how to use it for API automation in this blog post. In addition, we provided examples and code snippets to assist you in getting started with Rest Assured.

You can use Rest Assured to write tests that validate various aspects of an API, such as request and response headers, response status codes, response bodies, and more. Rest Assured also integrates with popular testing frameworks such as JUnit and TestNG.

You can easily automate your API testing and ensure that your API is functioning as expected by using Rest Assured. You can catch errors before they reach production by being able to write automated tests, saving time and effort in the long run.

Overall, Rest Assured is a valuable tool for API automation, and by following the examples and guidelines in this blog post, you can get started with Rest Assured and confidently begin automating your API tests.

 

3+
Sidharth Shukla

Sidharth Shukla

Currently working as a SDET. He is an Automation enabler who provides solutions that mitigates quality risk. Passionate about technical writing and contribution towards QA community.

Add comment