TL;DR
- REST Assured = Java library for REST API testing with fluent syntax
- Pattern:
given()(setup) →when()(action) →then()(verify)- Assertions: status codes, headers, JSON/XML body with JsonPath/XmlPath
- Integrates with JUnit 5, TestNG, Maven, Gradle
- Best for Java teams wanting code-based API tests
Best for: Java projects, teams using JUnit/TestNG, CI/CD pipelines Skip if: Non-Java stack or need GUI-based testing (use Postman) Reading time: 14 minutes
Your Java project needs API tests. Manual Postman testing doesn’t scale. You want tests in the same language as your application, running in CI/CD alongside unit tests.
REST Assured brings API testing into Java. Write tests with fluent syntax, validate responses with powerful matchers, integrate with existing test frameworks.
What is REST Assured?
REST Assured is a Java library that simplifies testing REST APIs. It provides a domain-specific language (DSL) for making HTTP requests and validating responses.
Why REST Assured:
- Java-native — integrates with JUnit, TestNG, Maven, Gradle
- Fluent syntax — readable given/when/then pattern
- Powerful validation — JsonPath, XmlPath, Hamcrest matchers
- Authentication — OAuth, basic auth, API keys built-in
- Request/response logging — debugging made easy
Setup
Maven
<dependencies>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>
</dependencies>
Gradle
testImplementation 'io.rest-assured:rest-assured:5.4.0'
testImplementation 'org.junit.jupiter:junit-jupiter:5.10.0'
Static Imports
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
Your First Test
Basic GET Request
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class ApiTest {
@Test
void shouldReturnUsers() {
given()
.baseUri("https://api.example.com")
.when()
.get("/users")
.then()
.statusCode(200)
.body("size()", greaterThan(0));
}
}
POST with JSON Body
@Test
void shouldCreateUser() {
String requestBody = """
{
"name": "John Doe",
"email": "john@example.com"
}
""";
given()
.baseUri("https://api.example.com")
.contentType("application/json")
.body(requestBody)
.when()
.post("/users")
.then()
.statusCode(201)
.body("id", notNullValue())
.body("name", equalTo("John Doe"));
}
Request Building
Headers and Query Params
given()
.baseUri("https://api.example.com")
.header("Authorization", "Bearer " + token)
.header("Accept", "application/json")
.queryParam("page", 1)
.queryParam("limit", 10)
.when()
.get("/users")
.then()
.statusCode(200);
Path Parameters
given()
.baseUri("https://api.example.com")
.pathParam("userId", 123)
.when()
.get("/users/{userId}")
.then()
.statusCode(200)
.body("id", equalTo(123));
Form Data
given()
.baseUri("https://api.example.com")
.contentType("application/x-www-form-urlencoded")
.formParam("username", "john")
.formParam("password", "secret")
.when()
.post("/login")
.then()
.statusCode(200);
Response Validation
Status and Headers
.then()
.statusCode(200)
.statusLine(containsString("OK"))
.header("Content-Type", "application/json")
.header("Cache-Control", containsString("max-age"));
JSON Body with JsonPath
// Response: {"user": {"id": 1, "name": "John", "roles": ["admin", "user"]}}
.then()
.body("user.id", equalTo(1))
.body("user.name", equalTo("John"))
.body("user.roles", hasSize(2))
.body("user.roles", hasItem("admin"));
Array Assertions
// Response: {"items": [{"id": 1}, {"id": 2}, {"id": 3}]}
.then()
.body("items.size()", equalTo(3))
.body("items.id", hasItems(1, 2, 3))
.body("items[0].id", equalTo(1))
.body("items.findAll { it.id > 1 }.size()", equalTo(2));
Extract Response Data
Response response = given()
.baseUri("https://api.example.com")
.when()
.get("/users/1")
.then()
.extract().response();
String name = response.jsonPath().getString("name");
int id = response.jsonPath().getInt("id");
List<String> roles = response.jsonPath().getList("roles");
Authentication
Basic Auth
given()
.auth().basic("username", "password")
.when()
.get("/protected")
.then()
.statusCode(200);
Bearer Token
given()
.auth().oauth2(accessToken)
.when()
.get("/api/resource")
.then()
.statusCode(200);
// Or with header
given()
.header("Authorization", "Bearer " + accessToken)
.when()
.get("/api/resource");
API Key
given()
.header("X-API-Key", apiKey)
.when()
.get("/api/data");
Test Organization
Base Configuration
import org.junit.jupiter.api.BeforeAll;
import io.restassured.RestAssured;
public class BaseApiTest {
@BeforeAll
static void setup() {
RestAssured.baseURI = "https://api.example.com";
RestAssured.basePath = "/v1";
// Enable logging for failed tests
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails();
}
}
Request/Response Specifications
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.ResponseSpecification;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.builder.ResponseSpecBuilder;
public class ApiSpecs {
public static RequestSpecification authRequest(String token) {
return new RequestSpecBuilder()
.setBaseUri("https://api.example.com")
.addHeader("Authorization", "Bearer " + token)
.setContentType("application/json")
.build();
}
public static ResponseSpecification successResponse() {
return new ResponseSpecBuilder()
.expectStatusCode(200)
.expectContentType("application/json")
.build();
}
}
// Usage
@Test
void shouldGetProfile() {
given()
.spec(ApiSpecs.authRequest(token))
.when()
.get("/profile")
.then()
.spec(ApiSpecs.successResponse())
.body("email", notNullValue());
}
TestNG Integration
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
public class UserApiTest {
@BeforeClass
public void setup() {
RestAssured.baseURI = "https://api.example.com";
}
@DataProvider(name = "userIds")
public Object[][] userIds() {
return new Object[][] {{1}, {2}, {3}};
}
@Test(dataProvider = "userIds")
public void shouldGetUser(int userId) {
given()
.pathParam("id", userId)
.when()
.get("/users/{id}")
.then()
.statusCode(200)
.body("id", equalTo(userId));
}
}
Logging
// Log request
given()
.log().all() // or .log().headers(), .log().body()
.when()
.get("/users");
// Log response
.then()
.log().all() // or .log().ifError(), .log().ifValidationFails()
.statusCode(200);
REST Assured with AI Assistance
AI tools can help write and maintain REST Assured tests.
What AI does well:
- Generate test methods from API documentation
- Create assertion chains for complex JSON
- Convert Postman collections to REST Assured
- Suggest edge case test scenarios
What still needs humans:
- Designing test strategy
- Understanding business validation rules
- Debugging authentication issues
- Performance test decisions
FAQ
What is REST Assured?
REST Assured is a Java library for testing REST APIs. It provides a fluent, domain-specific language (DSL) with the given/when/then pattern that makes tests readable. It integrates with JUnit 5, TestNG, Maven, and Gradle — fitting naturally into Java project workflows.
REST Assured vs Postman — which to use?
REST Assured is code-based (Java), runs in CI/CD, and lives in version control. Postman is GUI-based, great for exploration and manual testing. Use REST Assured when your team writes Java and needs automated pipeline tests. Use Postman for quick API exploration or teams without Java developers.
Can REST Assured test SOAP APIs?
REST Assured is designed specifically for REST/HTTP APIs. While you can send XML payloads, it lacks SOAP-specific features like WSDL parsing and envelope handling. For SOAP testing, use dedicated tools like SoapUI or Apache CXF.
Does REST Assured support authentication?
Yes, comprehensive support. Basic auth with .auth().basic(), OAuth 2.0 with .auth().oauth2(), digest auth, and custom headers for API keys or bearer tokens. Authentication can be configured per-request or globally via RestAssured.authentication.
Official Resources
See Also
- API Testing Tutorial - API testing fundamentals
- Postman Tutorial - GUI-based API testing
- TestNG Tutorial - Java test framework
- SoapUI Tutorial - SOAP/REST testing tool
