Project Setup (pom.xml)
Maven Dependency
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
<!-- Additional dependencies:
json-path
xml-path
json-schema-validator
testng
-->
Static Imports
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
The Given-When-Then Structure ⭐
given()
.baseUri("https://api.example.com")
.header("Content-Type", "application/json")
.body(payload)
.when()
.post("/users")
.then()
.statusCode(201)
.body("name", equalTo("Nav"));
Request Flow
| Block | Purpose |
given() |
Configure the request (URI, headers, authentication, parameters, body) |
when() |
Execute the HTTP request |
then() |
Validate the response |
Building Requests
HTTP Methods
.when().get("/users")
.when().post("/users")
.when().put("/users/1")
.when().patch("/users/1")
.when().delete("/users/1")
Query, Path & Form Parameters
given().queryParam("limit", 10)
.queryParam("skip", 5);
given().pathParam("id", 123)
.when().get("/users/{id}");
given().formParam("username", "admin");
Headers, Cookies & Content Types
given().header("Authorization", "Bearer " + token);
given().headers(headerMap);
given().cookie("session", value);
given().contentType(ContentType.JSON);
given().accept(ContentType.JSON);
Request Body
given().body(jsonString);
given().body(pojoObject);
given().body(new File("data.json"));
Response Validation
.then()
.statusCode(200)
.statusLine(containsString("OK"))
.contentType(ContentType.JSON)
.header("Server", notNullValue())
.cookie("session", notNullValue())
.body("id", equalTo(101))
.body("name", notNullValue())
.body("users.size()", equalTo(5))
.body("users.name", hasItems("Nav", "Alex"))
.time(lessThan(2000L));
Hamcrest Matchers
| Matcher | Purpose |
equalTo() |
Exact value comparison |
not(equalTo()) |
Negation |
containsString() |
Verify substring |
hasItem() / hasItems() |
Validate array contents |
hasSize() |
Validate collection size |
notNullValue() / nullValue() |
Null validation |
greaterThan() / lessThan() |
Numeric comparison |
everyItem() |
Validate every element |
Extraction & JsonPath ⭐
Extract a Single Value
String token =
given()
.body(credentials)
.when()
.post("/login")
.then()
.statusCode(200)
.extract()
.path("token");
Extract an Entire Response
Response response =
when()
.get("/users")
.then()
.extract()
.response();
int id = response.path("users[0].id");
String name =
response.jsonPath().getString("users[0].name");
List<String> names =
response.jsonPath().getList("users.name");
API Chaining
given()
.header("Authorization", "Bearer " + token)
.when()
.get("/profile")
.then()
.statusCode(200);
Logging
given().log().all();
.then().log().all();
.then().log().body();
.then().log().ifValidationFails();
Best Practice: Use
log().ifValidationFails()to keep reports clean while automatically logging failed requests and responses.
Authentication
given().auth().basic("user", "password");
given().auth().preemptive().basic("user", "password");
given().auth().oauth2(token);
given().header("Authorization", "Bearer " + token);
given().header("Cookie", "token=" + token);
Serialization (POJO)
Java Object → JSON
User user = new User("Nav", "nav@example.com");
given()
.contentType(ContentType.JSON)
.body(user)
.when()
.post("/users");
JSON → Java Object
User createdUser =
when()
.get("/users/1")
.then()
.extract()
.as(User.class);
JSON Schema Validation
.then()
.assertThat()
.body(matchesJsonSchemaInClasspath("user-schema.json"));
JSON Schema Validation helps detect:
- Missing fields
- Incorrect data types
- Contract changes
- Unexpected API response structures
Framework Patterns ⭐
Reusable RequestSpecification
RequestSpecification requestSpec =
new RequestSpecBuilder()
.setBaseUri("https://api.example.com")
.setContentType(ContentType.JSON)
.addHeader("Authorization", "Bearer " + token)
.build();
Reusable ResponseSpecification
ResponseSpecification responseSpec =
new ResponseSpecBuilder()
.expectStatusCode(200)
.expectContentType(ContentType.JSON)
.expectResponseTime(lessThan(2000L))
.build();
Using Specifications
given()
.spec(requestSpec)
.when()
.get("/users")
.then()
.spec(responseSpec);
Why Use Specifications? They eliminate repetitive setup and validations, making REST Assured automation frameworks cleaner, more maintainable, and easier to scale.
Advertisement
Go Deeper
Continue learning with:
- REST Assured Setup & Given-When-Then
- REST Assured Framework Design
- REST Assured vs Postman
- Complete REST Assured Guide
- Top REST Assured Interview Questions