Skip to main content
BlogsRestAssured CategorySoftware Testing guidance

REST Assured API Testing Tutorial: Automate RESTful APIs with Java

By February 4, 2021September 19th, 2025No Comments8 min read
How to Automate API Test Cases Using Rest Assured?

Behind every modern application—whether it’s a mobile app, an e-commerce site, or a SaaS platform—there are RESTful APIs exchanging data between services. The stability of these APIs directly impacts user experience, security, and business workflows. That’s why API testing is no longer optional; it’s a critical part of the development lifecycle. 

Manual tools like Postman help for quick validation, but they fall short when teams need repeatable, maintainable, and CI/CD-ready API tests. To keep up with agile delivery and frequent releases, organizations turn to automation. 

This is where REST Assured, a powerful Java library, changes the game. It enables teams to write API tests with minimal code, validate complex HTTP responses, and integrate seamlessly into existing testing frameworks like JUnit and TestNG. With built-in support for OAuth2, Bearer tokens, CSRF tokens, and the ability to run tests in parallel execution using TestNG or JUnit5, REST Assured ensures modern authentication and scalability needs are fully met.

 In this blog, we’ll explore what REST Assured is, how it works, and the step-by-step process of automating RESTful API test cases—from setup to advanced validation. 

How to Automate API Testing? 

API testing automation involves systematically validating APIs by simulating client requests and checking how the server responds. Unlike traditional testing approaches where you might click through UI flows, here the testing happens at the protocol level using HTTP methods such as GET, POST, PUT, and DELETE. 

To automate API tests, you generally follow this cycle: 

1. Defining request details: Each API call includes a base URI, an endpoint, and sometimes additional query parameters or path parameters. Depending on the method, it may also need a request body in JSON format or a specific header like Content-Type. 

2. Sending requests: Using a framework like REST Assured, you can simulate HTTP calls programmatically rather than relying on a manual client. This allows batch testing, regression testing, and running thousands of API requests automatically. 

Note: With the help of TestNG or JUnit5, API tests can also be executed in parallel to speed up overall execution time. 

3. Validating responses: The response from a server contains multiple components — the status code, headers, and response body (which may be a JSON string or JSON object). Validation involves checking that the response code is correct (e.g., 200 OK for success, 404 Not Found for invalid requests), the response body matches expected data, and the response time is within acceptable limits. 

4. Reporting: A robust automation framework does not stop at validation. It also generates detailed reports that help QA engineers and developers analyze failures quickly. These reports can be integrated into CI/CD pipelines so that failures are visible right after a deployment. 

By embedding this testing process into your pipelines, you create a safety net that ensures APIs remain functional as the application evolves. 

What is Rest Assured API Testing? 

REST Assured is a Java library designed specifically for testing RESTful APIs. Unlike writing raw HTTP requests using libraries like HttpURLConnection or Apache HttpClient, REST Assured simplifies the process by providing a fluent API and an intuitive syntax. This means you can write API tests that are readable, descriptive, and require minimal code.

For example, a simple GET request validation looks like this:

given() 

.baseUri(“https://api.example.com“) 

.queryParam(“id”, 1) 

.when() 

.get(“/users”) 

.then() 

.statusCode(200) 

.body(“name”, equalTo(“John Doe”)); 

This snippet shows REST Assured’s philosophy: abstracting the boilerplate code so testers can focus on what needs to be tested, not how the HTTP request is built. 

Why REST Assured Stands Out: 

  • It supports different HTTP methods (GET, POST, PUT, DELETE, PATCH). 
  • It handles request details like headers, cookies, authentication, and key-value pairs with ease. 
  • It validates response body, response headers, response code, and response time in a single test method. 
  • It integrates with JUnit, TestNG, and Maven projects, making it part of the broader Java ecosystem. 
  • It allows Behavior Driven Development (BDD) by adopting the given-when-then syntax, making tests both maintainable and readable. 
  • It supports advanced authentication mechanisms such as OAuth2, Bearer tokens, and CSRF tokens. 
  • It offers improved cookie handling and session management for stateful API testing. 

How Does REST Assured Work? 

At a deeper level, REST Assured works by wrapping the HTTP request-response cycle in an easy-to-use Java API. The workflow looks like this:

1. Request Setup 

  • Define the Base URI of the RESTful server.
  • Add headers such as Content-Type or authentication tokens.
  • Provide path parameters and query parameters as required.
  • Optionally, include a request body (JSON or XML).

2. Sending HTTP Requests 

REST Assured internally uses HTTP clients to send requests to the server. Whether it’s a GET method to fetch data or a POST request with JSON body, the syntax remains consistent.

3. Response Handling 

Once the RESTful server sends back a response, REST Assured provides structured access to:

  • Response status code (200, 400, 401, etc.)
  • Response headers (Content-Type, Authorization, etc.)
  • Response body (parsed into a json object or plain text).
  • Response time (measured in milliseconds).

4. Assertions 

Validation is the most powerful part. Using matchers, you can check: 

  • Whether the status code matches expectations.
  • Whether the response body contains expected values.
  • Whether the response headers include a specific header.
  • Whether the response time meets performance requirements.

This fluent API design reduces the learning curve and ensures test scripts remain concise and readable.

5. Handling Authentication
REST Assured simplifies testing secured APIs by supporting multiple authentication mechanisms out of the box, such as: 

  • Basic Authentication (preemptive and challenged). 
  • Digest Authentication for added security. 
  • Bearer Tokens (commonly used in OAuth2). 
  • OAuth 1 & OAuth 2 for modern API authentication flows. 
  • CSRF Token Handling for web applications requiring session-based validation. 

Why Use REST Assured for API Testing? 

The reasons for choosing REST Assured extend beyond just convenience. It directly impacts test quality, maintainability, and integration.

  • Maintainable API Tests: REST Assured promotes reusable components like request specifications and configurations, reducing duplication across test cases. 
  • Seamless Integration: It plugs easily into existing testing frameworks (JUnit, TestNG) and Maven projects, aligning with enterprise standards.
  • Minimal Code, Rich Validation: With REST Assured, validating a response often takes one or two lines of code compared to 15–20 lines in traditional HTTP client libraries. 
  • Support for Authentication: Many APIs require authentication. REST Assured handles basic authentication, tokens, and OAuth flows smoothly.
  • Fluent, BDD Style Syntax: The given(), when(), then() structure aligns with behavior-driven development, ensuring tests double as documentation.
  • CI/CD Friendly: REST Assured tests can run in Jenkins, GitHub Actions, or any pipeline, producing detailed reports and feedback for each deployment.

Because of these qualities, REST Assured is not just a testing tool but an enabler of a better development workflow.

Important Read: OWASP API Testing Guide

Steps to Test API with REST Assured 

Now let’s walk through the practical process of writing and executing API tests. 

1. Project Setup with Maven

Create a Maven project and add dependencies in pom.xml:

<dependency> 

<groupId>io.rest-assured</groupId> 

<artifactId>rest-assured</artifactId> 

<version>5.5.6</version> 

<scope>test</scope> 

</dependency> 

<dependency> 

<groupId>org.testng</groupId> 

<artifactId>testng</artifactId> 

<version>7.11.0</version> 

<scope>test</scope> 

</dependency> 

This ensures REST Assured integrates seamlessly with the Java ecosystem and your testing framework.

2. Writing Your First Test Class

import static io.restassured.RestAssured.*; 

import static org.hamcrest.Matchers.*; 

import org.testng.annotations.Test; 

public class UserAPITest { 

@Test 

public void testGetUser() { 

given() 

.baseUri(“https://api.example.com“) 

.header(“Content-Type”, “application/json”) 

.when() 

.get(“/users/1”) 

.then() 

.statusCode(200) 

.body(“name”, equalTo(“John Doe”)) 

.header(“Content-Type”, equalTo(“application/json; charset=utf-8”)); 

} 

} 

Here, we: 

  • Sent a GET request to /users/1.
  • Checked the status code.
  • Validated the response body and a specific header.

3. Testing Other HTTP Methods

  • POST Request with JSON Body: 

@Test 

public void testCreateUser() { 

String requestBody = “{ \”name\”: \”Jane Doe\”, \”email\”: \”jane@example.com\” }”; 

given() 

.baseUri(“https://api.example.com“) 

.header(“Content-Type”, “application/json”) 

.body(requestBody) 

.when() 

.post(“/users”) 

.then() 

.statusCode(201) 

.body(“id”, notNullValue()); 

} 

  • PUT Request with Path Parameter: 

@Test 

public void testUpdateUser() { 

String requestBody = “{ \”name\”: \”Jane Updated\” }”; 

given() 

.baseUri(“https://api.example.com“) 

.pathParam(“id”, 1) 

.header(“Content-Type”, “application/json”) 

.body(requestBody) 

.when() 

.put(“/users/{id}”) 

.then() 

.statusCode(200) 

.body(“name”, equalTo(“Jane Updated”)); 

} 

  • DELETE Request: 

@Test 

public void testDeleteUser() { 

given() 

.baseUri(“https://api.example.com“) 

.when() 

.delete(“/users/1”) 

.then() 

.statusCode(204); 

} 

4. Reusability and Best Practices

  • Define a Base URI once in a configuration class.
  • Use RequestSpecification objects to avoid repeating headers or authentication in every test.
  • Keep request details separate from validation logic for clarity.
  • Generate detailed reports (e.g., with Allure, Extent Reports) to improve visibility of test results.

This ensures your test suite remains scalable and maintainable over time.

Conclusion 

API testing is no longer optional — it’s a critical part of modern software development. With REST Assured, testers and developers can write intuitive, maintainable API tests that validate RESTful APIs with minimal code while covering status codes, headers, body content, and response times. 

Being a powerful Java library, it integrates naturally with existing Maven projects, testing frameworks, and CI/CD pipelines, making it ideal for both small teams and enterprise setups. With support for modern authentication, parallel execution, and integration with mocking tools, REST Assured continues to be one of the most reliable choices for API testing. By following the practices discussed here, you can ensure your REST APIs remain reliable, fast, and production-ready.

At Testrig Technologies, we specialize in delivering reliable API automation testing services using REST Assured and other modern frameworks. Our expert team ensures scalable, maintainable, and secure APIs that accelerate your development workflow.