Complete REST Assured Tutorial
REST Assured is a Java library for automating REST API tests in code. It gives you a readable given / when / then syntax for sending requests and validating responses, and it fits naturally into the same Maven, TestNG and Jenkins setup as your UI automation. Postman is ideal for exploring APIs by hand; REST Assured is what you use to build a maintainable, automated API regression suite.
This tutorial covers the essentials on one page — setup, your first test, the syntax you'll use daily and how a framework is structured — then links every REST Assured tutorial on the site in learning order.
Why REST Assured?
- Code-based — tests live in Git, are reviewed in pull requests and run in CI like any other code.
- Readable — given/when/then reads almost like a test case.
- Powerful validation — JSON and XML paths, Hamcrest matchers, schema validation, response time.
- Reusable — request and response specifications, POJOs and utilities keep large suites maintainable.
- Fits your stack — the same Java, TestNG and Maven you use for Selenium.
Not sure which tool to use when? See REST Assured vs Postman. New to APIs altogether? Start with The Complete API Testing Tutorial.
Step 1 — Set Up the Project
Create a Maven project (Java 11 or newer) and add these dependencies — use the latest versions from Maven Central:
<dependencies>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.5.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.10.2</version>
<scope>test</scope>
</dependency>
<!-- POJO serialization -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.2</version>
</dependency>
<!-- JSON schema validation (optional) -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>5.5.0</version>
<scope>test</scope>
</dependency>
</dependencies>
JsonPath and XmlPath are included with REST Assured automatically. Details: Setup & Syntax.
Step 2 — Your First API Test
This test calls JSONPlaceholder, a free public demo API, and validates the status code, two fields and the response time:
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
import org.testng.annotations.Test;
public class GetPostTest {
@Test
public void getPostById() {
given()
.baseUri("https://jsonplaceholder.typicode.com")
.when()
.get("/posts/1")
.then()
.statusCode(200)
.body("id", equalTo(1))
.body("userId", equalTo(1))
.time(lessThan(2000L));
}
}
Run it with mvn test. Every REST Assured test follows the same shape:
given()— request setup: base URI, headers, parameters, body, authentication.when()— the action: the HTTP method and endpoint.then()— validation: status, body, headers, time.
Step 3 — The Syntax You'll Use Every Day
| Task | Code |
|---|---|
| Send a JSON body | .contentType(ContentType.JSON).body(payload) |
| Path parameter | .pathParam("id", 42) with .get("/users/{id}") |
| Query parameter | .queryParam("page", 2) |
| Header | .header("Authorization", "Bearer " + token) |
| Check a field | .body("data.email", containsString("@")) |
| Check an array | .body("data", hasSize(6)) |
| Extract a value | .extract().path("data.id") |
| Deserialise to an object | .extract().as(User.class) |
| Log only on failure | .log().ifValidationFails() |
| Validate the schema | .body(matchesJsonSchemaInClasspath("schemas/user.json")) |
Keep the full list in the REST Assured Cheat Sheet, and see these in action in the REST Assured Visualizer.
Step 4 — Create, Extract, Reuse (API Chaining)
Real tests chain requests: create something, capture its ID, then use it in the next call.
int postId = given()
.baseUri("https://jsonplaceholder.typicode.com")
.contentType(ContentType.JSON)
.body("{\"title\": \"REST Assured\", \"body\": \"Learning\", \"userId\": 1}")
.when()
.post("/posts")
.then()
.statusCode(201)
.body("title", equalTo("REST Assured"))
.extract().path("id");
On a real API, you would now GET, update and delete that same resource using postId. (JSONPlaceholder only simulates writes, so the new post isn't actually stored.) Practise chaining in API Chaining, Negative & Data-Driven.
Step 5 — POJOs Instead of JSON Strings
Hand-written JSON strings get messy fast. A POJO (Plain Old Java Object) models the payload, and Jackson converts it to and from JSON automatically:
public class Post {
private String title;
private String body;
private int userId;
public Post() {}
public Post(String title, String body, int userId) {
this.title = title;
this.body = body;
this.userId = userId;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
public int getUserId() {
return userId;
}
}
given()
.contentType(ContentType.JSON)
.body(new Post("REST Assured", "Learning", 1))
.when()
.post("/posts")
.then()
.statusCode(201);
More: Serialization & POJO.
Step 6 — Specifications: the Heart of a Framework
Instead of repeating the base URI, headers and checks in every test, define them once:
RequestSpecification requestSpec = new RequestSpecBuilder()
.setBaseUri(System.getProperty("baseUri", "https://jsonplaceholder.typicode.com"))
.setContentType(ContentType.JSON)
.build();
ResponseSpecification okJson = new ResponseSpecBuilder()
.expectStatusCode(200)
.expectContentType(ContentType.JSON)
.build();
given()
.spec(requestSpec)
.when()
.get("/posts/1")
.then()
.spec(okJson);
Reading baseUri from a system property means the same tests run on any environment:
mvn test -DbaseUri=https://qa.example.com
What a REST Assured Framework Looks Like
src/test/java/
├── config/ → environment settings, base URIs (from properties or -D flags)
├── specs/ → RequestSpecification / ResponseSpecification builders
├── clients/ → one class per API area (UserClient, OrderClient)
├── models/ → POJOs for requests and responses
├── utils/ → auth/token helper, test data builders, JSON helpers
└── tests/ → TestNG test classes, grouped as smoke / regression
src/test/resources/
├── schemas/ → JSON schema files
└── testng.xml → suites, groups, parallel settings
Tests call client methods, clients use the specs, and nothing hard-codes URLs or tokens. Full walkthrough: REST Assured Framework Design.
The Learning Path
Part 1 — Foundations
- REST Assured Fundamentals — what it is, why it's used, where it fits in a framework.
- API Concepts for REST Assured — REST principles, methods, parameters and status codes.
- Setup & Syntax — Maven setup and the given/when/then structure.
- Sending Requests — GET, POST, PUT, PATCH, DELETE, parameters, headers and bodies.
Part 2 — Validation & Data
- Logging & Extraction — logging, and extracting values with JsonPath.
- Response Validation — status, headers, body and Hamcrest matchers.
- Serialization & POJO — Jackson/Gson, serialisation and deserialisation.
- Advanced Validation — nested JSON, arrays and complex assertions.
- JSON Schema Validation — contract checks.
Part 3 — Auth, Negative Testing & TestNG
- Authentication — Basic, Bearer tokens, OAuth 2.0 and JWT, dynamic tokens.
- Negative Testing & Error Handling — invalid input, error schemas, 4xx/5xx checks.
- TestNG Integration — data-driven tests, groups and execution control.
Part 4 — Framework & Real-Time
- Framework Design — specs, clients, POJOs and utilities.
- Real-Time Scenarios — chaining, end-to-end flows and scenario questions.
Part 5 — Hands-On Practice
Exercises against real demo APIs such as RESTful Booker, ReqRes and FakeStore:
- The Complete REST Assured Practice Roadmap ⭐ — 17 modules, 12 sprints
- API Understanding & Framework Setup
- HTTP Methods (CRUD) & Request Data
- Authentication, Token Handling & Response Validation
- API Chaining, Negative & Data-Driven
- Logging, CI/CD, Contract Testing & Senior Tasks
Part 6 — Interview Readiness
- Top 25 REST Assured Interview Questions — with code
- Top 30 API Testing Interview Questions and the API Interview Simulator
A 6-Week Study Plan
| Week | Focus | Outcome |
|---|---|---|
| 1 | API concepts, Postman basics, project setup | First GET test passing |
| 2 | All HTTP methods, parameters, headers, bodies | Full CRUD tests on a demo API |
| 3 | Validation, JsonPath extraction, logging | Meaningful assertions, not just status codes |
| 4 | POJOs, schema validation, authentication | Token-based, contract-checked tests |
| 5 | Specs, TestNG groups and data providers | A small, structured framework |
| 6 | Chaining, negative tests, CI with Jenkins | A portfolio-ready suite on GitHub |
From Real Projects
My API experience covers CRUD operations, HTTP methods, JSON path, and validating JSON and XML responses, and my automation work was in Java with TestNG. That combination is exactly what REST Assured builds on: HTTP calls in Java, JSON path for extracting values, and TestNG for running and grouping the tests. If you already know Selenium with TestNG, REST Assured fits into the same project structure. Testsigma supports web, mobile and API test automation, so understanding APIs was part of understanding the product I was testing. Build one complete test for a single endpoint first — request, status, body and schema — then reuse that pattern for the rest.
📚 Official documentation: REST Assured official site · REST Assured usage guide (GitHub wiki)
REST Assured Cheat Sheet: The Calls You'll Use Most
| Goal | REST Assured code |
|---|---|
| Query parameter | .queryParam("page", 2) |
| Path parameter | .pathParam("id", 7).get("/users/{id}") |
| Header | .header("X-Request-Id", "abc-123") |
| Bearer token | .auth().oauth2(token) |
| JSON body | .contentType(ContentType.JSON).body(userPojo) |
| Log everything (debugging) | .log().all() |
| Status code | .then().statusCode(201) |
| Field value | .body("data.email", equalTo("a@b.com")) |
| List size | .body("data", hasSize(6)) |
| Response time | .time(lessThan(2000L)) |
| Extract a value | .extract().path("id") |
int id =
given()
.baseUri("https://api.example.com")
.contentType(ContentType.JSON)
.body("{\"name\":\"asha\",\"job\":\"qa\"}")
.when()
.post("/users")
.then()
.statusCode(201)
.body("name", equalTo("asha"))
.extract().path("id");
The matchers (equalTo, hasSize, lessThan) come from Hamcrest: add import static org.hamcrest.Matchers.*; next to import static io.restassured.RestAssured.*;.
Frequently Asked Questions
Should I learn Postman or REST Assured first?
Postman first, to understand APIs quickly without code; then REST Assured to automate them in a framework that runs in CI. Most SDETs use both.
Do I need Java before learning REST Assured?
Yes. Core Java — OOP, collections, exception handling and writing simple classes — is essential. See Java for Testers.
What is the given–when–then syntax?
A BDD-style structure: given() sets up the request, when() sends it, and then() validates the response.
How do you validate an API contract?
With JSON schema validation: store the expected schema as a file and assert the response matches it using matchesJsonSchemaInClasspath().
How do you build a REST Assured framework?
Layer it: configuration, request/response specifications, API client classes, POJOs, utilities (auth, test data), TestNG tests and CI integration — so tests never hard-code URLs, tokens or payloads.
Can REST Assured test SOAP or GraphQL APIs?
It's built for REST, but it can send any HTTP request — including XML SOAP envelopes (validated with XmlPath) and GraphQL queries sent as JSON POST bodies.
Is REST Assured free?
Yes — it's open source under the Apache 2.0 licence.
What is REST Assured used for?
REST Assured is used to automate REST API tests in Java: sending requests, checking status codes, headers and JSON or XML bodies, and chaining calls, all inside a Maven project that runs with TestNG or JUnit in CI.
Is REST Assured a framework or a library?
A library. It provides the given/when/then API for HTTP testing; you build the framework around it with a test runner, specifications, POJOs, configuration and reporting.
Can REST Assured be used with JUnit instead of TestNG?
Yes. REST Assured doesn't depend on a test runner, so it works with JUnit 4, JUnit 5 or TestNG. Pick the one your UI tests already use.