Rest Assured Tutorial: API Automation with Java Step by Step
Set up Rest Assured 5 with Maven and TestNG, write GET and POST tests, reuse specs, validate schemas and structure a small API framework.
Most testers meet APIs through Postman. You send a request, read the JSON, add a few checks in the Tests tab and feel productive. Then the project needs 300 API checks running in Jenkins every night, reusing Java utilities from the UI framework, and Postman collections start to feel limiting. That is the point where this Rest Assured tutorial becomes useful.
Rest Assured is a Java library for testing REST APIs with a readable given-when-then style. Below you will set up a Maven project, write GET and POST tests, validate responses, reuse specifications, extract values for chained calls and organise everything into a small framework you can show in interviews.
Key takeaways
- Rest Assured lets you write API tests in Java with a fluent given, when, then syntax.
- You need Java 17 or 21, Maven, Rest Assured 5 and a test runner such as TestNG or JUnit 5.
- Use request and response specifications to avoid repeating base URLs, headers and common checks.
- Extract values from one response and pass them to the next request to test real workflows.
- Combine Rest Assured with POJOs, schema validation and CI to build a proper API automation framework.
What is Rest Assured and why testers use it
Rest Assured is an open-source Java library that wraps HTTP calls in a domain-specific language designed for testing. Instead of building HTTP clients by hand, you describe the request, send it and assert on the response in one chain.
Testers in India pick it for practical reasons. Many automation frameworks are already in Java, so API tests can live in the same repository, share utilities and run with the same TestNG suites. It is also a common skill in automation job descriptions, and interviewers often ask candidates to write a Rest Assured test on the spot.
If HTTP methods, status codes and headers still feel fuzzy, read the API fundamentals guide first. This tutorial assumes you know what a GET or POST request is.
Setting up the project
You need:
- JDK 17 or 21 installed and on your PATH.
- Maven 3.9 or later.
- An IDE such as IntelliJ IDEA Community or Eclipse.
Create a Maven project and add these dependencies to pom.xml. Check the latest patch versions on Maven Central when you set up; the major versions below are what matters.
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.10.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.1</version>
<scope>test</scope>
</dependency>
</dependencies>Jackson is needed when you send or receive Java objects as JSON. Hamcrest matchers come with Rest Assured, so you do not add them separately.
The examples use JSONPlaceholder, a free fake REST API that is handy for practice. It accepts POST, PUT and DELETE but does not actually save data, which is fine for learning.
Your first GET request test
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class PostsApiTest {
@Test
public void getSinglePostReturnsExpectedFields() {
given()
.baseUri("https://jsonplaceholder.typicode.com")
.when()
.get("/posts/1")
.then()
.statusCode(200)
.contentType("application/json")
.body("id", equalTo(1))
.body("userId", notNullValue())
.body("title", not(emptyString()));
}
}Read it aloud and it almost explains itself. given sets up the request, when sends it, then validates the response. The body checks use GPath expressions, so “id” refers to the id field in the JSON.
Run it from the IDE or with:
mvn testQuery parameters, path parameters and headers
Real APIs need parameters and headers. Rest Assured has a method for each.
@Test
public void commentsFilteredByPostId() {
given()
.baseUri("https://jsonplaceholder.typicode.com")
.queryParam("postId", 1)
.header("Accept", "application/json")
.when()
.get("/comments")
.then()
.statusCode(200)
.body("size()", greaterThan(0))
.body("postId", everyItem(equalTo(1)));
}
@Test
public void postByPathParam() {
given()
.baseUri("https://jsonplaceholder.typicode.com")
.pathParam("id", 5)
.when()
.get("/posts/{id}")
.then()
.statusCode(200)
.body("id", equalTo(5));
}“size()” checks the number of items in a JSON array at the root. “everyItem” confirms every comment belongs to post 1, which is a stronger check than looking at the first record only.
Sending a POST request with a JSON body
You can send the body as a string, a Map or a Java object. A POJO is the cleanest for larger payloads.
public class Post {
private int userId;
private String title;
private String body;
public Post() { }
public Post(int userId, String title, String body) {
this.userId = userId;
this.title = title;
this.body = body;
}
public int getUserId() { return userId; }
public String getTitle() { return title; }
public String getBody() { return body; }
}import io.restassured.http.ContentType;
@Test
public void createPostReturns201() {
Post newPost = new Post(1, "QA Jobs India", "Learning Rest Assured");
given()
.baseUri("https://jsonplaceholder.typicode.com")
.contentType(ContentType.JSON)
.body(newPost)
.when()
.post("/posts")
.then()
.statusCode(201)
.body("title", equalTo("QA Jobs India"))
.body("id", notNullValue());
}Rest Assured uses Jackson to convert the object into JSON automatically because the content type is JSON.
Extracting values and chaining requests
Workflow tests need data from one response in the next request. For example, create an order and then fetch it by id.
@Test
public void createThenFetchUserPosts() {
int userId =
given()
.baseUri("https://jsonplaceholder.typicode.com")
.when()
.get("/users/1")
.then()
.statusCode(200)
.extract().path("id");
given()
.baseUri("https://jsonplaceholder.typicode.com")
.queryParam("userId", userId)
.when()
.get("/posts")
.then()
.statusCode(200)
.body("userId", everyItem(equalTo(userId)));
}You can also extract the whole Response object and read fields with response.jsonPath().getString(“name”) when you need several values.
Reusing specifications to avoid repetition
Repeating baseUri and headers in every test gets old fast. Request and response specifications fix this.
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.filter.log.LogDetail;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.ResponseSpecification;
public final class Specs {
private Specs() { }
public static RequestSpecification request() {
return new RequestSpecBuilder()
.setBaseUri("https://jsonplaceholder.typicode.com")
.setContentType(ContentType.JSON)
.log(LogDetail.URI)
.build();
}
public static ResponseSpecification ok() {
return new ResponseSpecBuilder()
.expectStatusCode(200)
.expectContentType(ContentType.JSON)
.build();
}
}Now a test becomes:
@Test
public void usersListIsNotEmpty() {
given().spec(Specs.request())
.when().get("/users")
.then().spec(Specs.ok())
.body("size()", greaterThan(0));
}When the base URL changes between QA and staging, you edit one place. In a real framework, read it from a properties file or a system property.
Validating JSON schema
Field checks confirm values. Schema validation confirms structure: required fields, types and formats. Save a schema at src/test/resources/schemas/post.json:
{
"type": "object",
"required": ["userId", "id", "title", "body"],
"properties": {
"userId": { "type": "integer" },
"id": { "type": "integer" },
"title": { "type": "string" },
"body": { "type": "string" }
}
}import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
@Test
public void postMatchesSchema() {
given().spec(Specs.request())
.when().get("/posts/1")
.then().statusCode(200)
.body(matchesJsonSchemaInClasspath("schemas/post.json"));
}Common Rest Assured methods at a glance
| Method | Purpose |
|---|---|
| baseUri, basePath | Set the server and common path |
| queryParam, pathParam | Add parameters |
| header, contentType | Set headers and body type |
| body | Send a payload |
| auth().oauth2(token) | Bearer token authentication |
| statusCode | Assert the HTTP status |
| body(path, matcher) | Assert a JSON field with Hamcrest |
| extract().path | Read a value for later use |
| log().ifValidationFails() | Print request and response only on failure |
Turning tests into a framework
A tutorial project becomes interview-worthy when it has structure. A simple layout:
- config: environment properties and a class that reads them.
- specs: request and response specifications.
- models: POJOs for request and response bodies.
- clients: one class per resource, such as UserClient with methods like getUser(id).
- tests: TestNG classes that call clients and assert results.
- resources: JSON schemas and test data files.
Add logging only on failure, run tests through testng.xml, and wire the suite into Jenkins or GitHub Actions. The TestNG tutorial explains suites, groups and parallel execution that you will reuse here. Once this is on GitHub, it also makes a strong entry in your QA portfolio projects.
For deeper reference, the official Rest Assured site links to the usage guide and documentation.
Mistakes beginners make
- Hard-coding base URLs and tokens in every test instead of using config and specs.
- Asserting only the status code. A 200 with wrong data is still a bug.
- Writing tests that depend on each other’s order. Each test should set up its own data.
- Logging every request and response, which floods CI output. Log on failure instead.
- Ignoring negative tests such as invalid ids, missing fields and expired tokens.
🚀 Looking for API automation jobs?
QA Jobs India shares 100+ fresh QA & software testing openings every morning — manual, automation, API and remote roles.
See today’s QA jobs →FAQs
Is Rest Assured better than Postman?
They serve different needs. Postman is great for exploring APIs and quick manual checks. Rest Assured is better for large, code-based suites that live in version control, reuse Java utilities and run in CI. Many teams use both.
Does Rest Assured work with JUnit 5?
Yes. Rest Assured is independent of the test runner. You can use it with JUnit 5, TestNG or any other Java runner; only the annotations and assertions around it change.
Can Rest Assured test SOAP or GraphQL APIs?
It can send any HTTP request, so you can post XML for SOAP or a JSON query for GraphQL. It has XML path support for SOAP responses. For heavy GraphQL use, some teams add helper classes to build queries.
How do I handle authentication in Rest Assured?
Use auth().basic(user, pass) for basic auth, auth().oauth2(token) for bearer tokens, or header(“x-api-key”, key) for API keys. Read secrets from environment variables or CI secrets, never commit them to the repository.
What Rest Assured questions are asked in interviews?
Expect questions on given-when-then syntax, extracting values, request specifications, schema validation and handling authentication. Many interviewers ask you to write a GET and a POST test live. The Rest Assured interview questions guide covers common ones.
Conclusion
Rest Assured turns API testing into ordinary Java code that you can version, review and run in CI. Start with the GET and POST examples above, add specifications and a schema check, and push the project to GitHub within a week. Then extend it with negative tests and authentication, and you will have something concrete to discuss in your next API automation interview.
- 100+ fresh QA jobs daily + Direct HR email IDsLive every morning at 9 AM — apply straight to HR
- Weekly Mega Job Fair800+ QA jobs from India & around the world, every week
- Certified QA coursesUp to 3 courses included · all 17 for ₹500
- AI ATS Resume BuilderFree resume points included
- Full LinkedQA feedEvery post, fully unblurred
- Complete QA Material libraryInterview Q&A, cheat sheets, templates & roadmaps
Instant activation right after payment · One login for jobs, courses, resume & LinkedQA
💎 Get every QA opening, every day
Join QA Jobs India Premium for 100+ verified QA jobs daily with HR contact details.
QA Jobs Hub
Every QA job opening, company profile and career guide on QA Jobs India — India & Global, in one place.