🔍1. What is RestAssured?
RestAssured is a Java library designed for testing RESTful APIs. It simplifies HTTP request-response validation and integrates well with popular Java testing frameworks like TestNG and JUnit.
🔍What is a REST API?
A REST API, or Representational State Transfer API, is a design approach that relies on HTTP methods for communicating with web services. It allows two systems (like a frontend and backend, or two applications) to communicate over the internet using simple HTTP calls.
- Client-Server: The client (e.g., browser or app) makes requests, and the server responds.
- Stateless: Each request from the client contains all the information the server needs.
- Cacheable: Responses can be cached to improve performance.
- Uniform Interface: Relies on common HTTP operations such as GET, POST, PUT, and DELETE.
- Resource-Based: Everything is a resource, identified by a URI (e.g., /users/1).
Key Concepts of REST:-
- No need for extensive boilerplate code
- Fluent, BDD-style syntax
- Supports JSON/XML
- Easy integration with TestNG, Maven, Jenkins, etc.
- Built-in support for logging, authentication, headers, cookies, etc.
Why use RestAssured?
Add the following dependencies in your pom.xml:
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.10.1</version>
<scope>test</scope>
</dependency>
</dependencies>
📌Purpose: To fetch data from the server. Fetch data using query parameters (like pagination).
public void testGetUsers() {
RestAssured
.given()
.baseUri(“https://reqres.in”)
.basePath(“/api/users”)
.queryParam(“page”, 2)
.when()
.get()
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body(“page”, equalTo(2))
.log().all();
}
✅Explanation: Sends a GET request to fetch users on page 2. Validates status code and response type.
📌Purpose: Create a new user using POST.
public void testCreateUser() {
String requestBody = “{ \”name\”: \”Akash\”, \”job\”: \”QA Engineer\” }”;
RestAssured
.given()
.baseUri(“https://reqres.in”)
.basePath(“/api/users”)
.contentType(ContentType.JSON)
.body(requestBody)
.when()
.post()
.then()
.statusCode(201)
.body(“name”, equalTo(“Akash”))
.body(“job”, equalTo(“QA Engineer”))
.log().body();
}
✅Explanation: Sends a POST request with a JSON body. Validates the returned name and job values.
📌Purpose: Update existing user details.
public void testUpdateUser() {
String requestBody = “{ \”name\”: \”Akash\”, \”job\”: \”Senior QA\” }”;
RestAssured
.given()
.baseUri(“https://reqres.in”)
.basePath(“/api/users/2”)
.contentType(ContentType.JSON)
.body(requestBody)
.when()
.put()
.then()
.statusCode(200)
.body(“job”, equalTo(“Senior QA”))
.log().body();
}
✅Explanation: Sends a PUT request to update user data. Validates the updated value in the response.
📌Purpose: Update existing user details
public void testUpdateUser() {
String requestBody = “{ \”job\”: \”Lead QA\” }”;
RestAssured
.given()
.baseUri(“https://reqres.in”)
.basePath(“/api/users/2”)
.contentType(ContentType.JSON)
.body(requestBody)
.when()
.patch()
.then()
.statusCode(200)
.body(“job”, equalTo(“Lead QA”))
.log().body();
}
✅Explanation: Sends a PATCH request to update user data. Validates the updated value in the response.
📌Purpose: To delete a resource from the server.
public void testDeleteUser() {
RestAssured
.given()
.baseUri(“https://reqres.in”)
.basePath(“/api/users/2”)
.when()
.delete()
.then()
.statusCode(204); // No Content
}
✅Explanation: Sends a DELETE request to remove a user. Checks that the status code is 204.
📌Purpose: Access an endpoint protected by basic authentication.
public void testBasicAuth() {
RestAssured
.given()
.auth().basic(“admin”, “password”)
.when()
.get(“https://example.com/protected”)
.then()
.statusCode(200);
}
✅Explanation: Adds basic authentication and validates the response.
📌Purpose: Send custom headers and cookies in the request.
public void testHeadersAndCookies() {
RestAssured
.given()
.baseUri(“https://reqres.in”)
.header(“Custom-Header”, “MyValue”)
.cookie(“SessionID”, “abc123”)
.when()
.get(“/api/users?page=2”)
.then()
.statusCode(200);
}
✅Explanation: Custom headers or cookies can simulate authenticated or special request types.
📌Purpose: Extract and validate specific fields from JSON response.
public void testJsonPathValidation() {
Response response = RestAssured
.given()
.queryParam(“page”, 2)
.when()
.get(“https://reqres.in/api/users”);
String email = response.jsonPath().getString(“data[0].email”);
System.out.println(“Email: ” + email);
}
✅Explanation: Extracts the first user’s email and prints it for verification.
📌Purpose: Structure your tests using setup methods and assertions.
public void setup() {
RestAssured.baseURI = “https://reqres.in”;
}
@Test
public void testUsersList() {
RestAssured
.given()
.basePath(“/api/users”)
.queryParam(“page”, 2)
.when()
.get()
.then()
.statusCode(200);
}
✅Explanation: Initializes base URI only once for all tests using @BeforeClass.
📌Purpose: View request/response for debugging.
public void testWithLogging() {
RestAssured
.given()
.log().all()
.baseUri(“https://reqres.in”)
.basePath(“/api/users”)
.queryParam(“page”, 2)
.when()
.get()
.then()
.log().all()
.statusCode(200);
}
✅Explanation: Enables logging for request and response to debug or understand flow.
Rest Assured uses a fluent interface, allowing you to chain method calls. Here’s a breakdown of some common methods:
- given(): Starts the test specification
- baseUri(), basePath(): Set the base URL and path for the request
- param(), queryParam(): Add query parameters
- header(), headers(): Set request headers
- body(): Set the request body
- when(): Marks the start of the request section
- get(), post(), put(), delete(): HTTP methods
- then(): Starts the validation section
- statusCode(): Asserts the response status code
- body(): Validates the response body
Parameterised tests allow you to run the same test with different inputs, increasing your test coverage:
@DataProvider(name = “userIds”)
public Object[][] createUserIds() {
return new Object[][] {{1}, {2}, {3}, {4}, {5}};
}
@Test(dataProvider = “userIds”)
public void testMultipleUsers(int userId) {
given()
.pathParam(“id”, userId)
.when()
.get(“https://api.example.com/users/{id}”)
.then()
.statusCode(200)
.body(“id”, equalTo(userId))
.body(“name”, notNullValue());
}
}
This test will run five times, once for each user ID provided by the data provider.
Handling file upload and download is a common use case in API testing. RestAssured provides fluent APIs to deal with both scenarios smoothly.
✅Use Case: Upload an image, text file, or document via a multipart/form-data API.
public void uploadFileTest() {
File fileToUpload = new File(“src/test/resources/sample.txt”);
RestAssured
.given()
.baseUri(“https://api.example.com”)
.basePath(“/upload”)
.multiPart(“file”, fileToUpload)
.contentType(“multipart/form-data”)
.when()
.post()
.then()
.statusCode(200)
.body(“message”, equalTo(“File uploaded successfully”))
.log().body();
}
✅Use Case: Download a file from the API and save it locally.
public void downloadFileTest() throws IOException {
byte[] fileBytes = RestAssured
.given()
.baseUri(“https://api.example.com”)
.basePath(“/download/sample.pdf”)
.when()
.get()
.then()
.statusCode(200)
.extract()
.asByteArray();
// Save to file
Path destination = Paths.get(“downloads/sample_downloaded.pdf”);
Files.createDirectories(destination.getParent()); // Create folder if not exists
Files.write(destination, fileBytes);
System.out.println(“File downloaded to: ” + destination.toAbsolutePath());
}
✅Check content-type of the downloaded file:
public void validateDownloadedFileType() {
Response response = RestAssured
.given()
.baseUri(“https://api.example.com”)
.basePath(“/download/sample.pdf”)
.when()
.get();
// Check Content-Type
String contentType = response.getHeader(“Content-Type”);
Assert.assertEquals(contentType, “application/pdf”);
// Check file size is greater than 0
Assert.assertTrue(response.getBody().asByteArray().length > 0);
}
Operation Syntax
- Upload a File
.multiPart("paramName", new File("path"))
- Add Form Field
.multiPart("key", "value")
- Set Type
.contentType("multipart/form-data")
- Download File
.extract().asByteArray() + Files.write()
- Check File Type
response.getHeader("Content-Type")
In RestAssured, ResponseSpecification is a way to define reusable response validations. Rather than repeating .statusCode(200).contentType(JSON)
in every test, you can create a specification and apply it wherever needed.
ResponseSpecBuilder is a builder class used to create a ResponseSpecification easily. You define all your expected response elements once and reuse them in multiple tests.
- Reduces code duplication
- Increases test readability
- Centralises common response validations
import org.testng.annotations.Test;
public class GetUserTest extends BaseTest {
@Test
public void validateGetUsersWithSpec() {
RestAssured
.given()
.baseUri(“https://reqres.in”)
.basePath(“/api/users”)
.queryParam(“page”, 2)
.when()
.get()
.then()
.spec(responseSpec) // Reuse the spec
.log().body();
}
}
RestAssured is a powerful and intuitive tool for REST API testing in Java. It simplifies the process of writing readable, maintainable, and scalable API tests with its fluent syntax and rich feature set. By leveraging concepts like ResponseSpecification, ResponseSpecBuilder, and chaining methods, you can reduce redundancy, enhance test reliability, and ensure comprehensive coverage of API behaviors. Whether you’re testing simple GET requests or complex authentication flows, RestAssured provides the flexibility and control needed for modern API testing. Coupled with frameworks like TestNG and tools like Maven, it integrates smoothly into CI/CD pipelines and supports enterprise-grade test automation.