Introduction

What is REST Assured?

REST Assured is a popular Java-based library used to test RESTful APIs. It makes API testing easy by providing a simple and readable way to send HTTP requests and validate responses.


When building or testing software, APIs (Application Programming Interfaces) allow different systems to communicate with each other. REST Assured helps you verify if these APIs work correctly by automating the testing process.

Why Use REST Assured?

  • Easy to Use: REST Assured simplifies the process of making API requests and checking the responses.
  • Comprehensive: It supports all common HTTP methods like GET, POST, PUT, DELETE, and PATCH.
  • Flexible: Works with JSON, XML, and other data formats.
  • Powerful Assertions: Allows you to validate response status codes, headers, and body content.
  • Integration: Works well with popular testing frameworks like JUnit and TestNG.

Key Features of REST Assured

  1. Simplified API Testing: Write clean and readable tests without dealing with low-level HTTP details.
  2. Support for Different HTTP Methods: Perform GET, POST, PUT, DELETE, PATCH, and other requests.
  3. Flexible Request and Response Handling: Handle JSON, XML, and other formats seamlessly.
  4. Authentication Support: Supports Basic, Digest, OAuth, and OAuth 2.0 authentication.
  5. Assertions and Validations: Validate status codes, headers, and response bodies with ease.
  6. Integration with Testing Frameworks: Works with JUnit, TestNG, and other Java testing frameworks.
  7. Error Handling and Logging: Provides built-in support to capture logs and manage errors.

How REST Assured Works

REST Assured works by sending HTTP requests to an API and checking the responses. Here is a simple process:

  1. Send a Request: Make a request to an API (e.g., GET or POST).
  2. Receive a Response: Get the API response (status code, headers, body).
  3. Validate the Response: Check if the response matches your expectations (e.g., 200 OK status, correct JSON body).
Java
Copy
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class ApiTest {
    public static void main(String[] args) {
        given()
            .when().get("http://192.xxx.xx.xxx:8080/books")
            .then().statusCode(200)
            .body("size()", greaterThan(0));
    }
}

In this example:

  • given() sets up the request.
  • when() sends the request.
  • then() validates the response (status code 200 and a non-empty response body).

When to Use REST Assured

  • Automating API Tests: Validate RESTful APIs automatically.
  • Regression Testing: Ensure APIs still work after code changes.
  • Performance Testing: Measure API response times and load.
  • Continuous Integration (CI): Run API tests as part of your CI pipeline.