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

Purushoth Kumar

Senior Automation Testing Engineer

Posted on

25/01/2023

Update on

25/04/2025

Next Review on

24/07/2025

How To Perform Api Test Automation Using Rest Assured

Rest Assured is a powerful and easy-to-use Java library that helps automate the testing of RESTful APIs. It lets you send requests, check responses, and validate results with minimal code. Whether you’re a tester or developer, it’s a great tool for building reliable and maintainable API tests. In this blog, we’ll guide you through the basics of API Test Automation Testing using Rest Assured—from setting up your project and writing your first tests, to handling authentication and validating different types of responses. We’ll also share best practices to help you get the most out of your API tests.

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.

Key Features:Rest Assured enables you to examine essential components of HTTP responses, including:

  • Status Codes: These indicate the result of the API request, such as 200 for success, 404 for not found, and 500 for server errors.
  • Response Body: The actual data returned by the API, often in JSON or XML format.
  • Headers: Metadata included in the response, such as content type and authentication details.
  • Response Time: The duration taken for the server to process and return a response.

It integrates seamlessly with Java-based frameworks, provides easy-to-read syntax, and generates clear, detailed 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

To set up your testing environment, create a Maven project:

Steps:

  • Open your IDE (IntelliJ IDEA, Eclipse, etc.).
  • Navigate to File → New → Project.
  • Select Maven Archetype.
  • Enter the project name and click 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>5.5.0</version>
       <scope>test</scope>
    </dependency>
    
    

    Anatomy of a REST API

    A REST API consists of the following components:

    URI:

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

    Uri Components Of Http Request

    • Base URI: The root address of the API, e.g., https://api.example.com/
    • Endpoints: The specific paths where resources are exposed, e.g., /users, /orders, /products.
    • Base Path: The common path prefix for all API endpoints, e.g., /api/v1.
    • Query Parameters: Key-value pairs appended to the URL, used for filtering, sorting, and pagination, e.g., ?page=2&limit=10.
    • Path Parameters: Dynamic values within the URL, used to specify resources, e.g., /users/{id} where {id} is replaced with an actual user ID.
    • HTTP Methods:
      • GET: Retrieves data.
      • POST: Creates new resources.
      • PUT: Updates an existing resource.
      • DELETE: Removes a resource.
    • Header:Headers provide metadata for requests and responses, such as:
      • Content-Type: Specifies the format of the request body (e.g., application/json)
      • Authorization: Includes authentication details (e.g., Bearer token)
    • Request Body: The body contains the payload (data) sent in POST, PUT, or PATCH requests. It can be in JSON, XML, or other formats.
    • Response: Includes status codes, response body, and headers.

    Send the request over the network

    You can send payload data using a String or a JSON object. A JSON file can also be used as the request body payload.

    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.

    import io.restassured.RestAssured;
    import io.restassured.specification.RequestSpecification;
    import org.json.JSONObject;
    import org.junit.Test;
    
    import static io.restassured.RestAssured.*;
    import static org.hamcrest.Matchers.*;
    
    public class RestAssuredExample {
    
        // Set the base URI once for all test methods
        static {
            RestAssured.baseURI = "https://reqres.in/api";
        }
    
        // Common request setup with JSON header
        RequestSpecification request = given().header("Content-Type", "application/json");
    
        // Test method for Basic Authentication
        @Test
        public void testBasicAuth() {
            // This test uses basic authentication (username and password) to access a protected resource
            given()
                .auth().basic("username", "password")
            .when()
                .get("/protected-resource")
            .then()
                .statusCode(200)
                .log().all();
        }
    
        // Test method for OAuth2 Authentication
        @Test
        public void testOAuth2() {
            // This test uses an OAuth2 token to access a protected resource
            given()
                .auth().oauth2("your-access-token")
            .when()
                .get("/protected-resource")
            .then()
                .statusCode(200)
                .log().all();
        }
    
        // Test method for Bearer Token Authentication
        @Test
        public void testBearerToken() {
            // This test uses a bearer token in the Authorization header to access a protected resource
            request.header("Authorization", "Bearer your-token")
            .when()
                .get("/protected-resource")
            .then()
                .statusCode(200)
                .log().all();
        }
    
        // Test method for a simple GET request
        @Test
        public void testGETRequest() {
            // This test sends a GET request to fetch details of user with ID 2
            request
            .when()
                .get("/users/2")
            .then()
                .statusCode(200)
                .body("data.id", equalTo(2))
                .log().all();
        }
    
        // Test method for a POST request
        @Test
        public void testPOSTRequest() {
            // This test sends a POST request to create a new user
            JSONObject requestParams = new JSONObject();
            requestParams.put("name", "John");
            requestParams.put("job", "Tester");
    
            request.body(requestParams.toString())
            .when()
                .post("/users")
            .then()
                .statusCode(201)
                .log().all();
        }
    
        // Test method for a PUT request
        @Test
        public void testPUTRequest() {
            // This test sends a PUT request to update user details
            JSONObject requestParams = new JSONObject();
            requestParams.put("name", "John Updated");
            requestParams.put("job", "Senior Tester");
    
            request.body(requestParams.toString())
            .when()
                .put("/users/2")
            .then()
                .statusCode(200)
                .log().all();
        }
    
        // Test method for a DELETE request
        @Test
        public void testDELETERequest() {
            // This test sends a DELETE request to remove the user with ID 2
            request
            .when()
                .delete("/users/2")
            .then()
                .statusCode(204)
                .log().all();
        }
    }
    
    

    Code Explanation:

    Authentication Mechanisms

    Authentication is required for accessing protected APIs. Rest Assured provides multiple ways to authenticate requests.

    a) Basic Authentication

    
    given()
        .auth().basic("username", "password")
    .when()
        .get("/protected-resource")
    .then()
        .statusCode(200)
        .log().all();
    
    
    • given(): Initializes the request.
    • .auth().basic(“username”, “password”): Sets Basic Authentication with a username and password.
    • .when().get(“/protected-resource”): Sends a GET request to the endpoint.
    • .then().statusCode(200): Validates that the response status code is 200 (OK).
    • .log().all(): Logs the full request and response details.

    b) OAuth2 Authentication

    
    given()
        .auth().oauth2("your-access-token")
    .when()
        .get("/protected-resource")
    .then()
        .statusCode(200)
        .log().all();
    
    
    • .auth().oauth2(“your-access-token”): Uses an OAuth2 access token for authentication.
    • The rest of the code follows the same pattern as Basic Authentication.

    c) Bearer Token Authentication

    
    request.header("Authorization", "Bearer your-token")
    .when()
        .get("/protected-resource")
    .then()
        .statusCode(200)
        .log().all();
    
    
    • .header(“Authorization”, “Bearer your-token”): Manually adds an Authorization header with a Bearer token.
    • Useful when a direct .auth() method is not available or required.
    • The rest of the code follows the standard GET request structure.

    CRUD Operations with Rest Assured

    CRUD operations allow interaction with a REST API by creating, reading, updating, and deleting resources.

    a) GET Request (Read Data)

    
    request
    .when()
        .get("/users/2")
    .then()
        .statusCode(200)
        .body("data.id", equalTo(2))
        .log().all()
    
    
    • .when().get(“/users/2”): Sends a GET request to fetch user details.
    • .statusCode(200): Ensures the response status is 200 OK.
    • .body(“data.id”, equalTo(2)): Validates that the response contains id = 2.
    • .log().all(): Logs request and response details.

    b) POST Request (Create Data)

    
    JSONObject requestParams = new JSONObject();
    requestParams.put("name", "John");
    requestParams.put("job", "Tester");
    
    request.body(requestParams.toString())
    .when()
        .post("/users")
    .then()
        .statusCode(201)
        .log().all();
    
    
    • JSONObject requestParams = new JSONObject();: Creates a JSON object to hold request data.
    • requestParams.put(“name”, “John”);: Adds name field to JSON.
    • requestParams.put(“job”, “Tester”);: Adds job field to JSON.
    • .body(requestParams.toString()): Sets the request body to the JSON string.
    • .when().post(“/users”): Sends a POST request to create a user.
    • .statusCode(201): Ensures response is 201 Created (successful resource creation).
    • .log().all(): Logs the request and response details.

    c) PUT Request (Update Data)

    
    JSONObject requestParams = new JSONObject();
    requestParams.put("name", "John Updated");
    requestParams.put("job", "Senior Tester");
    
    request.body(requestParams.toString())
    .when()
        .put("/users/2")
    .then()
        .statusCode(200)
        .log().all();
    
    
    • Creates a JSON object similar to the POST request.
    • Updates user details (name and job).
    • .when().put(“/users/2”): Sends a PUT request to update user 2.
    • .statusCode(200): Ensures response is 200 OK (successful update).
    • .log().all(): Logs all details.

    d) DELETE Request (Remove Data)

    
    request
    .when()
        .delete("/users/2")
    .then()
        .statusCode(204)
        .log().all();
    
    
    • .when().delete(“/users/2”): Sends a DELETE request for user 2.
    • .statusCode(204): Ensures the response status is 204 No Content, indicating successful deletion.
    • .log().all(): Logs request and response details.

    Best Practices for API Testing with Rest Assured

    • Use Logging – Always log requests and responses for better debugging.
    • Validate Responses – Use assertions to verify status codes, response time, and body content.
    • Parameterize Tests – Avoid hardcoded values; use dynamic data where possible.
    • Use Environment Variables – Store credentials and base URLs securely.
    • Test Negative Scenarios – Validate how APIs behave with incorrect inputs.

    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.

    Frequently Asked Questions

    • What is Rest Assured?

      Rest Assured is a Java library used for testing RESTful APIs. It simplifies sending HTTP requests and validating responses, making it ideal for API automation testing.

    • Why should I use Rest Assured for API testing?

      Rest Assured offers an easy-to-read syntax, integrates well with Java-based frameworks like TestNG and JUnit, and supports all HTTP methods. It also allows seamless validation of status codes, headers, response bodies, and response times.

    • Do I need to know Java to use Rest Assured?

      Yes, basic knowledge of Java is required since Rest Assured is a Java-based tool.

    • Can I automate both positive and negative test cases with Rest Assured?

      Yes, you can and should automate both. Rest Assured makes it easy to validate both successful responses and how the API handles invalid inputs or edge cases.

    • Is Rest Assured suitable for CI/CD pipelines?

      Definitely. Rest Assured tests can be integrated into Jenkins, GitLab CI, or other CI/CD tools to run automated API checks as part of your development workflow.

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