REST Assured API Testing Tutorial
โก Smart Summary
REST Assured establishes itself as a Java-based open-source library that streamlines REST API automation testing. The framework empowers quality engineers to validate complex JSON responses, headers, status codes, and response times using clean BDD-style syntax with seamless Maven integration.

What is Rest Assured?
Rest Assured enables you to test REST APIs using java libraries and integrates well with Maven. It has very efficient matching techniques, so asserting your expected results is also pretty straight forward. Rest Assured has methods to fetch data from almost every part of the request and response no matter how complex the JSON structures are.
For the testing community, API Automation Testing is still new and niche. The JSON complexities keep API testing unexplored. But that does not make it less important in the testing process. Rest Assured.io framework has made it very simple using core java basics, making it a very desirable thing to learn.
Why need Rest-Assured?
Imagine you open your Google Maps view and look for a place you want to go. You immediately see nearby restaurants, commute options from leading travel providers, and many choices at your fingertips. We all know these are not Google products, so how does Google manage to display them? It uses the exposed APIs of these providers. Now, if you are asked to test this kind of setup, even before the UI is built or is under development, testing APIs becomes extremely important. Testing them repeatedly with different data combinations makes it a very suitable case for automation.
Earlier, teams used dynamic languages such as Groovy and Ruby to achieve this, and it was challenging. Hence API testing was not widely explored by functional testers.
However, with Rest Assured, automation testing of APIs and sending simple HTTPS requests with user-friendly customizations becomes simple if one has a basic background of Java. It is helpful for understanding API testing and integration testing. Rest Assured gives strong confidence on the backend while front-end testers can focus on the UI and client-side operations. Rest Assured is open source, and the constant addition of methods and libraries has made it a great choice for API automation.
REST Assured vs Postman: Key Differences
Both REST Assured and Postman validate REST APIs, yet each fits a different stage of the testing lifecycle. Selecting the right tool depends on your team skills, project scope, and integration needs.
| Aspect | REST Assured | Postman |
|---|---|---|
| Type | Java library for code-based automation | GUI-based API client with scripting support |
| Best Use Case | Continuous integration pipelines and regression suites | Manual exploration and quick API checks |
| Skill Requirement | Core Java knowledge required | Minimal coding; uses JavaScript snippets |
| Reporting | Integrates with TestNG, JUnit, and Allure | Built-in run summaries via Newman CLI |
Many teams use Postman for early prototyping and switch to REST Assured for automated regression once the API contract stabilizes.
How to Setup of Rest Assured.io with Eclipse
Setting up REST Assured involves three core dependencies: Java, an IDE, and Maven. Follow the steps below in order to avoid build errors later.
Step 1) Install Java. Refer to this guide
Step 2) Download an IDE to begin: eclipse
Step 3) Install Maven and set up your eclipse. Refer here.
Setup Rest Assured
- Create a Maven Project in your IDE. We are using IntelliJ, but you will get a similar structure on any IDE you may be using.
- Open your POM.xml.
Project structure for a REST Assured Maven workspace
For Rest Assured.io: For Java version < 9 users:
Add the below dependency to your POM.xml:
<dependency> <groupId>io.rest-assured</groupId> <artifactId>json-path</artifactId> <version>4.2.0</version> <scope>test</scope> </dependency> <dependency> <groupId>io.rest-assured</groupId> <artifactId>xml-path</artifactId> <version>4.2.0</version> <scope>test</scope> </dependency> <dependency> <groupId>io.rest-assured</groupId> <artifactId>json-schema-validator</artifactId> <version>4.2.0</version> <scope>test</scope> </dependency>
For Rest Assured.io: For Java version 9+ users:
<dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured-all</artifactId> <version>4.2.0</version> <scope>test</scope> </dependency>
Troubleshooting:
In case you see errors and are not sure if the dependencies got downloaded correctly, follow these steps:
- Perform a Maven build to import all dependencies. You will find help on Maven set up on Guru99.
- If errors persist, run a Maven clean followed by a Maven install. The build should complete without errors.
- Add the below imports in your Java class and confirm there are no compile errors.
import io.restassured.RestAssured.*; import io.restassured.matcher.RestAssuredMatchers.*; import org.hamcrest.Matchers.*;
First simple Rest Assured script
With dependencies in place, you can now write your first script. The framework follows a Behavior-Driven Development (BDD) style that reads almost like English.
Syntax:
The syntax of Rest Assured.io is the most readable part of the framework, as it is very BDD-like and understandable.
Given().
param("x", "y").
header("z", "w").
when().
Method().
Then().
statusCode(XXX).
body("x", "y", equalTo("z"));
Explanation:
| Code | Explanation |
|---|---|
| Given() | The ‘Given’ keyword lets you set a background. Here, you pass the request headers, query and path params, body, and cookies. This is optional if these items are not needed in the request. |
| When() | The ‘when’ keyword marks the premise of your scenario. For example, ‘when’ you get/post/put something, do something else. |
| Method() | Substitute this with any of the CRUD operations (get/post/put/delete). |
| Then() | Your assert and matcher conditions go here. |
Now that you have the setup and some background to the syntax, let’s create our first simple test. It is okay if the structure seems new to you, as you code further and interpret each line, you will get the hang of it.
What will you fetch?
Open your browser and hit – https://demo.guru99.com/V4/sinkministatement.php?CUSTOMER_ID=68195&PASSWORD=1234!&Account_No=1. Ensure you see something as below.
Sample API response captured by REST Assured
In case you get an error on the browser when you try to get a response for the request:
- Check whether you used HTTPS or HTTP. Your browser may have settings that block insecure websites.
- Check whether any proxy or firewall is blocking your browser from opening the website.
*Note – you did not use any headers here, no body, and no cookie. It was a URL, and you are getting content from the API rather than posting or updating any existing content. That makes it a GET call. Remember this to understand our first test better.
The Objective of your test:
The goal of the script is to print the same output on your IDE console as what you received on the browser through Rest Assured.
Let us code this with the below steps:
Getting the response Body
Step 1) Create a class named “myFirstRestAssuredClass”.
Step 2) Create a method called “getResponseBody”.
Step 3) Similar to the structure learned earlier of given, when, and then, type the below code:
given(). -> No headers required, no query or path param.
when(). -> No specific condition setup.
get(‘https://demo.guru99.com/V4/sinkministatement.php?CUSTOMER_ID=68195&PASSWORD=1234!&Account_No=1‘). -> only the URL needs to be supplied.
then(). -> No specific assertions required.
log(). all() -> Once all the response is fetched, log response, headers, and essentially everything that the request returns to you.
public static void getResponseBody(){
given().when().get("https://demo.guru99.com/V4/sinkministatement.php?CUSTOMER_ID=68195&PASSWORD=1234!&Account_No=1").then().log()
.all();
}
Now notice that the URL used is long and less readable. Looking closely, you will notice that 3 query parameters are being used:
- Customer_ID
- Password
- Account_No
Rest Assured helps us pass every part (query, path, header param) separately, making the code more readable and easy to maintain. Also, we can parameterize the data from an external file as required.
For using query param, we go back to our definition of the syntax and see that all of them are passed as a part of given.
public static void getResponseBody(){
given().queryParam("CUSTOMER_ID","68195")
.queryParam("PASSWORD","1234!")
.queryParam("Account_No","1")
.when().get("https://demo.guru99.com/V4/sinkministatement.php").then().log()
.body();
}
**Note that we used “body” instead of “all”; this helps us extract only the body of the response.
Output:
Getting the response status code
The next method we will script is to get the status code and put an assertion to validate it.
Step 1) Create a method called getResponseStatus().
Step 2) Use the same request structure used above. Copy and paste it.
Step 3) Instead of logging it, use the ‘getStatusCode’ inbuilt method of Rest Assured to fetch the status code value.
Step 4) In order to assert that your status code is 200, use the keywords – assertThat().statusCode(expectedCode).
**Note – URL is a variable used for simplicity. URL holds the entire API request URL.
public static void getResponseStatus(){
int statusCode= given().queryParam("CUSTOMER_ID","68195")
.queryParam("PASSWORD","1234!")
.queryParam("Account_No","1") .when().get("https://demo.guru99.com/V4/sinkministatement.php").getStatusCode();
System.out.println("The response status is "+statusCode);
given().when().get(url).then().assertThat().statusCode(200);
}
Output:
Business Need
One of the basic rules of automation is that we have to put checkpoints so that the test proceeds only if all the required conditions are met. In API testing, the most basic validation is to check if the status code of the request is in 2XX format.
The complete code, so far:
import java.util.ArrayList;
import static io.restassured.RestAssured.*;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
public class myFirstRestAssuredClass {
final static String url="https://demo.guru99.com/V4/sinkministatement.php?CUSTOMER_ID=68195&PASSWORD=1234!&Account_No=1";
public static void main(String args[]) {
getResponseBody();
getResponseStatus();
; }
//This will fetch the response body as is and log it. given and when are optional here
public static void getResponseBody(){
given().when().get(url).then().log()
.all();
given().queryParam("CUSTOMER_ID","68195")
.queryParam("PASSWORD","1234!")
.queryParam("Account_No","1") .when().get("https://demo.guru99.com/V4/sinkministatement.php").then().log().body();
}
public static void getResponseStatus(){
int statusCode= given().queryParam("CUSTOMER_ID","68195")
.queryParam("PASSWORD","1234!")
.queryParam("Account_No","1")
.when().get("https://demo.guru99.com/V4/sinkministatement.php").getStatusCode();
System.out.println("The response status is "+statusCode);
given().when().get(url).then().assertThat().statusCode(200);
}
}
*Note:
- 200 is a successful response for this scenario. At times, you may need the request to fail, in which case you might use 4XX or 5XX. Try changing the status code by supplying invalid parameters and check.
- When we assert a condition, there will be no printing on the console unless there is an error.
Script to fetch different parts of a response
Beyond response body and status code, REST Assured also exposes headers, response time, and content type through chainable extractor methods. The keyword ‘extract’ is essential for fetching these specific parts.
Header
Rest Assured is a very straightforward language, and fetching headers is just as simple. The method name is headers(). Like before, we will create a standalone method to do the same.
public static void getResponseHeaders(){
System.out.println("The headers in the response "+
get(url).then().extract()
.headers());
}
Please note that ‘given().when()’ is skipped here, and the code line starts from get(). This is because there is no precondition or verification made before hitting the request and getting a response. In such cases, it is optional to use the same.
Output :
Business Need:
Quite often, you would need to use the authorization token or a session cookie for the subsequent request, and these details are mostly returned as headers of the response.
Response Time
To get the time needed to fetch the response from the backend or other downstream systems, Rest Assured provides a method called ‘timeIn’ with a suitable timeUnit to get the time taken to return the response.
public static void getResponseTime(){
System.out.println("The time taken to fetch the response "+get(url)
.timeIn(TimeUnit.MILLISECONDS) + " milliseconds");
}
Output:
Business Need:
A very important feature of testing APIs is their response time, which measures the performance of the application. The time taken for your call may take more or less time depending on your internet speed, the performance of the API at that time, server load, and other factors impacting the time.
Content-Type
You can get the content type of the response returned using the method “contentType()”.
public static void getResponseContentType(){
System.out.println("The content type of response "+
get(url).then().extract()
.contentType());
}
Output
Business Need:
At times, getting the content type is essential for ensuring there are no security gaps for any cross-origin threats and for confirming that the content passed is as per the standards of the API.
Fetch Individual JSON Element
From the given response, you are asked to calculate the total amount. You need to fetch every amount and sum it up.
Steps:
Step 1) The amount field is within an array with key “statements”, which is in turn in the list with key “result”.
Step 2) Rest Assured provides a mechanism to reach the values in the API using “path”.
Step 3) The path to reach amounts is “result.statements.AMOUNT”. Think of it like XPath in Selenium.
Step 4) Fetch all amounts in a collection, then loop through all values to calculate the sum.
public static void getSpecificPartOfResponseBody(){
ArrayList<String> amounts = when().get(url).then().extract().path("result.statements.AMOUNT") ;
int sumOfAll=0;
for(String a:amounts){
System.out.println("The amount value fetched is "+a);
sumOfAll=sumOfAll+Integer.valueOf(a);
}
System.out.println("The total amount is "+sumOfAll);
}
Note: Since the amount value is a string data type, we convert it to an integer for summation.
Output:
Best Practices for REST Assured Test Automation
Once you understand the basics, applying disciplined patterns keeps your suite reliable as the API surface grows. The practices below help teams avoid flaky tests and maintenance overhead.
- Centralize the Base URL: Store the base URI and authentication tokens in a single configuration class or properties file. This avoids duplication and simplifies environment switching.
- Use Request and Response Specifications: Build reusable RequestSpecBuilder and ResponseSpecBuilder objects. They reduce boilerplate when many tests share common headers or assertions.
- Validate JSON Schema: Combine REST Assured with the json-schema-validator module to confirm contract integrity. Schema checks catch breaking changes before they reach downstream consumers.
- Externalize Test Data: Store payloads in JSON files or use data providers from TestNG. Hard-coded data quickly becomes stale.
- Run Independent Tests: Each test should set up and tear down its own data. Order-dependent suites fail unpredictably in parallel CI runs.
- Capture Logs Selectively: Use log().ifError() in stable suites and log().all() during debugging. Verbose logs slow CI pipelines and obscure real issues.
- Plug into CI/CD: Trigger REST Assured suites through Maven Surefire or Failsafe in Jenkins, GitHub Actions, or GitLab. Run smoke checks on every commit and full regression overnight.
Adopting these habits early turns API automation into a long-term asset rather than a fragile bottleneck.


