REST Assured Tutorial A to Z — STAD Solution
☕ Complete Tutorial

REST Assured

API Testing A to Z

Master REST Assured from scratch — setup, requests, assertions, authentication, and real-world best practices. Built for beginners and intermediate testers.

⏱️ ~4 hrs 📚 14 Topics 💻 Code Examples 🧪 Quiz Each Section ☕ Java Based
What is REST Assured?
REST Assured is an open-source Java library used to test and validate REST APIs. It was created by Johan Haleby and is widely used in the software testing industry because it makes writing API tests simple, readable, and powerful — even if you are not an expert in Java.

Think of it this way: when you test a website manually, you open a browser, go to a URL, and check what shows up. REST Assured does the same thing — but for APIs, and automatically.

💡 Simple Analogy: Imagine you order food from a restaurant (client). The waiter (API) takes your order to the kitchen (server) and brings back your food (response). REST Assured is like an automated quality checker that verifies the food delivered is exactly what you ordered — correct item, correct quantity, correct price.

Key Facts About REST Assured

PropertyDetails
LanguageJava
Created byJohan Haleby
TypeOpen-source library (Apache 2.0 license)
Used forTesting REST APIs — GET, POST, PUT, DELETE, PATCH
Works withTestNG, JUnit, Maven, Gradle
GitHub Stars6,700+ stars — widely used in enterprise projects
Official siterest-assured.io

Why REST Assured? What makes it special?

  • Readable syntax (BDD style): Uses Given/When/Then format — your test reads like English.
  • No complex setup: Just add a Maven dependency and you're ready to write tests.
  • Built-in JSON & XML support: Parse, extract, and validate response data easily.
  • Works with all HTTP methods: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS.
  • Authentication support: Basic Auth, OAuth, OAuth2, Bearer Token — built in.
  • Integrates with CI/CD: Works with Jenkins, GitHub Actions, and any pipeline tool.
🧪
Section Quiz — What is REST Assured?
Test your understanding
Multiple Choice
Q1. What is REST Assured primarily used for?
A Testing web UI (browsers)
B Testing REST APIs
C Load testing databases
D Mobile app testing
True / False
Q2. REST Assured requires you to be an expert Java developer to use it.
A True
B False
REST & HTTP Basics

Before writing any test, you must understand what a REST API is and how HTTP works. This is the foundation on which REST Assured is built.

REST stands for Representational State Transfer. It is an architectural style for building web services. A REST API allows two applications to communicate with each other over the internet using standard HTTP methods.

HTTP Methods — The 5 You Must Know

MethodPurposeExample
GETRead / Fetch dataGet list of all users
POSTCreate new dataCreate a new user account
PUTUpdate (full replace)Update all details of a user
PATCHUpdate (partial)Update only the email of a user
DELETERemove dataDelete a user by ID

HTTP Status Codes — What Do They Mean?

CodeMeaningWhen you see it
200 OKSuccessGET request fetched data correctly
201 CreatedCreatedPOST request created new resource
204 No ContentSuccess, no bodyDELETE was successful
400 Bad RequestClient errorYou sent wrong/missing data
401 UnauthorizedNot authenticatedNo token or wrong credentials
403 ForbiddenNo permissionToken valid but no access rights
404 Not FoundResource missingWrong endpoint or ID doesn't exist
500 Internal Server ErrorServer crashedBug on the server side

What is JSON? (REST Assured uses it a lot)

JSON (JavaScript Object Notation) is the most common format for sending and receiving data in REST APIs. It is easy to read and write.

json — Sample API Response
{
  "id": 1,
  "name": "Rahul Sharma",
  "email": "rahul@example.com",
  "role": "tester",
  "active": true
}
🧪
Section Quiz — REST & HTTP
Test your understanding
Multiple Choice
Q1. Which HTTP method should you use to CREATE a new resource?
A GET
B POST
C DELETE
D PATCH
Multiple Choice
Q2. What status code indicates that the API request was successful and a resource was CREATED?
A 200
B 201
C 404
D 500
True / False
Q3. A 401 status code means the resource was not found on the server.
A True
B False
Installation & Project Setup

REST Assured is a Java library. You add it to your project using Maven or Gradle. Below is the recommended Maven setup using TestNG as the test framework.

1

Install Java JDK 11+

Download from adoptium.net. Verify: java -version in terminal.

2

Install IntelliJ IDEA or Eclipse

IntelliJ Community (free) is recommended for beginners. Download from jetbrains.com.

3

Create a Maven Project

In IntelliJ: File → New Project → Maven. This creates a pom.xml file automatically.

4

Add REST Assured dependencies

Paste the dependencies shown below inside your pom.xml file.

Maven Dependencies (pom.xml)

xml — pom.xml dependencies
<!-- Add inside <dependencies> tag in pom.xml -->

<!-- REST Assured -->
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.4.0</version>
    <scope>test</scope>
</dependency>

<!-- TestNG -->
<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>7.9.0</version>
    <scope>test</scope>
</dependency>

<!-- JSON Schema Validation (optional but useful) -->
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>json-schema-validator</artifactId>
    <version>5.4.0</version>
</dependency>
⚠️ Important: Always use the same version number for all REST Assured dependencies to avoid version conflict errors.
🧪
Section Quiz — Setup
Test your understanding
Multiple Choice
Q1. Which file is used to add REST Assured dependencies in a Maven project?
A build.gradle
B pom.xml
C settings.xml
D config.json
True / False
Q2. REST Assured can be used without Java.
A True
B False
Your First REST Assured Test

Let's write your very first API test. We will use the free public API https://reqres.in — a dummy REST API designed for testing. No sign-up needed.

What we are testing: Send a GET request to https://reqres.in/api/users/2 and verify that the response status code is 200 and the user's email contains "janet".
java — FirstTest.java
import io.restassured.RestAssured;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import org.testng.annotations.Test;

public class FirstTest {

    @Test
    public void testGetUser() {

        given()
            .log().all()            // log the request details
        .when()
            .get("https://reqres.in/api/users/2")
        .then()
            .log().all()            // log the response details
            .statusCode(200)      // assert status code is 200
            .body("data.email", containsString("janet"));
    }
}
Run this test: Right-click on the test method in IntelliJ → "Run testGetUser". If everything is set up correctly, you will see "1 test passed" in the output.
🧪
Section Quiz — First Test
Multiple Choice
Q1. Which import is essential for using REST Assured static methods like given(), when(), then()?
A import io.restassured.response.Response;
B import static io.restassured.RestAssured.*;
C import org.testng.Assert;
D import java.net.HttpURLConnection;
True / False
Q2. .log().all() in REST Assured helps you see request and response details in the console.
A True
B False
Given / When / Then — BDD Syntax

REST Assured uses the BDD (Behavior Driven Development) syntax. This is the heart of REST Assured — every test you write will follow this structure.

📋

given()

Set up the request — headers, params, body, auth, base URL.

🚀

when()

Send the actual HTTP request — get(), post(), put(), delete().

then()

Verify the response — status code, body values, headers.

java — BDD Structure Example
given()
    .baseUri("https://reqres.in")
    .header("Content-Type", "application/json")

.when()
    .get("/api/users?page=2")

.then()
    .statusCode(200)
    .body("page", equalTo(2))
    .body("data.size()", greaterThan(0));
💡 Pro Tip: Think of it as a sentence — "GIVEN I have these request details, WHEN I call this endpoint, THEN I expect this response." This makes your tests self-documenting.
🧪
Section Quiz — BDD Syntax
Multiple Choice
Q1. In REST Assured's BDD syntax, where do you add request headers and authentication?
A given()
B when()
C then()
D validate()
True / False
Q2. BDD stands for "Browser Driven Development".
A True
B False
GET, POST, PUT, DELETE, PATCH

REST Assured supports all HTTP methods. Here are examples for each, using the reqres.in public test API.

GET — Fetch Data

java — GET Request
@Test
public void getUsers() {
    given()
    .when()
        .get("https://reqres.in/api/users/1")
    .then()
        .statusCode(200)
        .body("data.id", equalTo(1));
}

POST — Create Data

java — POST Request
@Test
public void createUser() {
    String body = "{ \"name\": \"Rahul\", \"job\": \"tester\" }";

    given()
        .header("Content-Type", "application/json")
        .body(body)
    .when()
        .post("https://reqres.in/api/users")
    .then()
        .statusCode(201)
        .body("name", equalTo("Rahul"));
}

PUT — Full Update

java — PUT Request
@Test
public void updateUser() {
    String body = "{ \"name\": \"Rahul Updated\", \"job\": \"senior tester\" }";

    given()
        .header("Content-Type", "application/json")
        .body(body)
    .when()
        .put("https://reqres.in/api/users/2")
    .then()
        .statusCode(200)
        .body("name", equalTo("Rahul Updated"));
}

DELETE — Remove Data

java — DELETE Request
@Test
public void deleteUser() {
    given()
    .when()
        .delete("https://reqres.in/api/users/2")
    .then()
        .statusCode(204);  // 204 means deleted, no content returned
}
🧪
Section Quiz — HTTP Methods
Multiple Choice
Q1. What status code do you typically expect after a successful DELETE request?
A 200
B 201
C 204
D 404
True / False
Q2. A PUT request typically replaces the entire resource, while PATCH only updates specific fields.
A True
B False
Request Parameters & Headers

Most real-world APIs require you to pass query parameters, path parameters, and headers with your requests. REST Assured makes all of these easy.

Query Parameters

Query parameters appear after ? in the URL. Example: /api/users?page=2&per_page=5

java — Query Parameters
given()
    .queryParam("page", 2)
    .queryParam("per_page", 5)
.when()
    .get("https://reqres.in/api/users")
.then()
    .statusCode(200)
    .body("page", equalTo(2));

Path Parameters

Path parameters are part of the URL itself. Example: /api/users/{userId}

java — Path Parameters
given()
    .pathParam("userId", 3)
.when()
    .get("https://reqres.in/api/users/{userId}")
.then()
    .statusCode(200)
    .body("data.id", equalTo(3));

Headers

java — Request Headers
given()
    .header("Content-Type", "application/json")
    .header("Accept", "application/json")
    .header("x-api-key", "your-api-key-here")
.when()
    .get("https://api.example.com/products")
.then()
    .statusCode(200);
🧪
Section Quiz — Params & Headers
Multiple Choice
Q1. Which method is used to pass a dynamic value in the URL path like /users/{id}?
A .queryParam()
B .pathParam()
C .formParam()
D .header()
True / False
Q2. Query parameters appear after the "?" in a URL.
A True
B False
Sending Request Body (POST / PUT)

When creating or updating data, you need to send a request body — usually in JSON format. REST Assured gives you multiple ways to do this.

Method 1: Plain String Body

java — String body
String requestBody = "{" +
        "\"name\": \"Priya\"," +
        "\"job\": \"QA Engineer\"" +
        "}";

given()
    .contentType("application/json")
    .body(requestBody)
.when()
    .post("https://reqres.in/api/users")
.then()
    .statusCode(201);

Method 2: HashMap Body (Recommended)

java — HashMap body
import java.util.HashMap;

HashMap<String, String> map = new HashMap<>();
map.put("name", "Priya");
map.put("job", "QA Engineer");

given()
    .contentType("application/json")
    .body(map)
.when()
    .post("https://reqres.in/api/users")
.then()
    .statusCode(201)
    .body("name", equalTo("Priya"));
💡 Why HashMap is better: You don't have to worry about escaping quotes in strings. The HashMap is automatically converted to proper JSON by REST Assured internally.
🧪
Section Quiz — Request Body
Multiple Choice
Q1. Which content type header is most commonly used when sending JSON body in REST Assured?
A text/html
B application/json
C application/xml
D multipart/form-data
True / False
Q2. REST Assured can automatically convert a Java HashMap to JSON format in the request body.
A True
B False
Response Assertions with Hamcrest

REST Assured uses Hamcrest matchers to write assertions. Hamcrest is a matching library that provides human-readable assertion methods.

Common Hamcrest Matchers

MatcherWhat it checksExample
equalTo(x)Exact match.body("name", equalTo("Rahul"))
containsString(x)String contains.body("email", containsString("@"))
not(x)Negation.body("role", not("admin"))
hasSize(n)Collection size.body("data", hasSize(6))
greaterThan(n)Value comparison.body("total", greaterThan(10))
lessThan(n)Value comparison.body("count", lessThan(100))
notNullValue()Not null.body("id", notNullValue())
hasItem(x)Array contains item.body("tags", hasItem("java"))
java — Multiple Assertions
given()
.when()
    .get("https://reqres.in/api/users?page=1")
.then()
    .statusCode(200)
    .body("page", equalTo(1))
    .body("per_page", equalTo(6))
    .body("data", hasSize(6))
    .body("data[0].email", containsString("@"))
    .body("data[0].id", notNullValue())
    .body("total", greaterThan(5));
🧪
Section Quiz — Assertions
Multiple Choice
Q1. Which matcher checks that a JSON array field has exactly 6 items?
A equalTo(6)
B greaterThan(6)
C hasSize(6)
D containsString(6)
True / False
Q2. REST Assured uses Hamcrest matchers to write readable assertions.
A True
B False
JSON Path Extraction

Sometimes you don't just want to verify a value — you want to extract it and use it in the next test (like extracting a token from a login response). REST Assured makes this simple.

java — Extracting values from response
import io.restassured.response.Response;

@Test
public void extractUserData() {
    Response response = given()
    .when()
        .get("https://reqres.in/api/users/2")
    .then()
        .statusCode(200)
        .extract().response();

    // Extract individual values
    String email = response.jsonPath().getString("data.email");
    int id    = response.jsonPath().getInt("data.id");
    String name  = response.jsonPath().getString("data.first_name");

    System.out.println("Email: " + email);
    System.out.println("ID: " + id);
    System.out.println("Name: " + name);
}

Chain Extraction (Shorter syntax)

java — Direct extraction
String token = given()
    .contentType("application/json")
    .body("{ \"email\": \"eve.holt@reqres.in\", \"password\": \"cityslicka\" }")
.when()
    .post("https://reqres.in/api/login")
.then()
    .statusCode(200)
    .extract().path("token");   // extract the token directly

System.out.println("Token: " + token);
💡 Real-world use: Extract the login token from Step 1, then pass it as a header in Step 2. This is called test chaining and is extremely common in API automation.
🧪
Section Quiz — JSON Path
Multiple Choice
Q1. Which method is used to extract a value directly from the response chain in REST Assured?
A .body().get()
B .response().read()
C .extract().path()
D .get().value()
True / False
Q2. You can extract a token from a login API response and use it in the next test request.
A True
B False
Authentication — Basic, Bearer & OAuth

Most production APIs require authentication. REST Assured has built-in support for the most common authentication methods.

1. Basic Authentication

java — Basic Auth
given()
    .auth().basic("username", "password")
.when()
    .get("https://api.example.com/profile")
.then()
    .statusCode(200);

2. Bearer Token (most common)

java — Bearer Token
String token = "eyJhbGciOiJIUzI1NiJ9..."; // JWT token

given()
    .header("Authorization", "Bearer " + token)
.when()
    .get("https://api.example.com/dashboard")
.then()
    .statusCode(200);

3. OAuth 2.0

java — OAuth2
given()
    .auth().oauth2("your-oauth2-access-token")
.when()
    .get("https://api.example.com/data")
.then()
    .statusCode(200);
🧪
Section Quiz — Authentication
Multiple Choice
Q1. Which header value format is used for Bearer Token authentication?
A "Token yourtoken"
B "Bearer yourtoken"
C "Basic yourtoken"
D "Auth yourtoken"
True / False
Q2. REST Assured's .auth().basic() method sends the username and password in the Authorization header.
A True
B False
Base URI & RequestSpecification

In real projects, you don't want to repeat the base URL and headers in every test. RequestSpecification lets you define common settings once and reuse them everywhere.

Setting Base URI globally

java — Global Base URI
import io.restassured.RestAssured;
import org.testng.annotations.BeforeClass;

public class BaseTest {

    @BeforeClass
    public void setup() {
        // Set once, used in all tests in this class
        RestAssured.baseURI = "https://reqres.in";
        RestAssured.basePath = "/api";
    }
}

RequestSpecification — Reusable Config

java — RequestSpecification
import io.restassured.specification.RequestSpecification;
import io.restassured.builder.RequestSpecBuilder;

RequestSpecification spec = new RequestSpecBuilder()
    .setBaseUri("https://reqres.in")
    .setBasePath("/api")
    .addHeader("Content-Type", "application/json")
    .addHeader("Authorization", "Bearer " + token)
    .build();

// Use in any test:
given(spec)
.when()
    .get("/users/1")   // base URL is already set in spec
.then()
    .statusCode(200);
🏗️ Framework Tip: Create a BaseTest.java class and put your RequestSpecification there. Make all test classes extend BaseTest. This is the standard industry practice.
🧪
Section Quiz — RequestSpec
Multiple Choice
Q1. What is the benefit of using RequestSpecification in REST Assured?
A It makes tests run faster
B Reuse common config (URL, headers, auth) across all tests
C It generates test reports automatically
D It replaces the need for TestNG
True / False
Q2. Setting RestAssured.baseURI globally means you don't need to repeat the base URL in every test.
A True
B False
Logging & Debugging Tests

When your test fails, you need to understand what exactly was sent and received. REST Assured's logging features make debugging very easy.

Log MethodWhat it logs
.log().all()Full request or response (most used for debugging)
.log().body()Only the request or response body
.log().headers()Only headers
.log().status()Only status code and status line
.log().ifError()Logs only when the test fails (best for CI pipelines)
.log().ifValidationFails()Logs only when an assertion fails
java — Logging Example
given()
    .log().all()               // log everything in the request
    .header("Accept", "application/json")
.when()
    .get("https://reqres.in/api/users/2")
.then()
    .log().ifValidationFails() // log response only if test fails
    .statusCode(200);
⚠️ Best practice for CI/CD: Use .log().ifValidationFails() instead of .log().all() in your committed code. This reduces log noise in passing tests.
🧪
Section Quiz — Logging
Multiple Choice
Q1. Which logging method is BEST to use in a CI/CD pipeline to reduce noise?
A .log().all()
B .log().body()
C .log().headers()
D .log().ifValidationFails()
True / False
Q2. .log().all() in the given() section logs the response body.
A True
B False
Best Practices & Framework Structure

Following best practices from day one will make you job-ready and your tests maintainable, scalable, and professional.

Recommended Project Structure

text — Maven Project Structure
src/
├── test/
│   ├── java/
│   │   ├── base/
│   │   │   └── BaseTest.java        ← RequestSpec, setup, teardown
│   │   ├── tests/
│   │   │   ├── UserTests.java       ← Actual test methods
│   │   │   └── AuthTests.java
│   │   ├── utils/
│   │   │   └── ConfigReader.java    ← Read config.properties
│   │   └── pojo/
│   │       └── User.java            ← POJO classes for request/response
│   └── resources/
│       ├── config.properties        ← base URL, credentials
│       └── testng.xml               ← TestNG suite configuration
└── pom.xml

Top 10 Best Practices

  • 1
    Use RequestSpecification — Never repeat base URL and headers in every test.
  • 2
    Store configs in properties file — Don't hardcode URLs, tokens, or credentials in test code.
  • 3
    Use POJO classes — Map request/response JSON to Java objects using Jackson or Gson for cleaner code.
  • 4
    One assertion per test (where possible) — Makes failures easier to identify.
  • 5
    Use @BeforeClass / @AfterClass — Set up and tear down test data cleanly.
  • 6
    Use .log().ifValidationFails() — Not .log().all() in committed code.
  • 7
    Data-driven with @DataProvider — Run same test with multiple inputs using TestNG DataProvider.
  • 8
    Name tests clearly — e.g. verifyGetUserReturns200WhenValidId(), not test1().
  • 9
    Integrate with Allure or ExtentReports — Generate beautiful HTML reports for stakeholders.
  • 10
    Integrate with CI/CD — Run tests automatically on Jenkins or GitHub Actions on every code push.
🏆
Final Quiz — Best Practices
Complete the course!
Multiple Choice
Q1. Where should you store the base URL and credentials in a professional REST Assured framework?
A Hardcode directly in every test method
B In a config.properties file, read via a utility class
C In the pom.xml file
D In comments in each test file
Multiple Choice
Q2. Which TestNG annotation is used to run setup code ONCE before all tests in a class?
A @BeforeTest
B @BeforeClass
C @BeforeMethod
D @BeforeSuite
True / False
Q3. REST Assured can be integrated with CI/CD tools like Jenkins or GitHub Actions to run tests automatically.
A True
B False
🎉 Congratulations! You have completed the REST Assured A to Z Tutorial by STAD Solution. You now have the knowledge to build a professional API testing framework from scratch!

Ready to advance your QA career? 🚀

Hands-on QA training covering REST Assured, Selenium, Playwright, Postman, JIRA, Manual Testing & more — taught by industry practitioners.

Visit stadsolution.com →
🧪 REST Assured 🌐 Selenium 🎭 Playwright 📮 Postman 📋 JIRA ✅ Manual Testing