API TESTING WITH JAVA ยท QUICK REFERENCE GUIDE
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.4.0</version>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>5.4.0</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.1</version>
</dependency>import static io.restassured.RestAssured.*;
import static io.restassured.matcher
.RestAssuredMatchers.*;
import static org.hamcrest.Matchers.*;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.http.ContentType;
import io.restassured.specification
.RequestSpecification;
import io.restassured.specification
.ResponseSpecification;RestAssured.baseURI = "https://api.example.com";
RestAssured.basePath = "/v1";
RestAssured.port = 8080;
// Skip SSL certificate validation
RestAssured.useRelaxedHTTPSValidation();
// Reset all global config
RestAssured.reset();import io.restassured.builder
.RequestSpecBuilder;
RequestSpecification spec =
new RequestSpecBuilder()
.setBaseUri("https://api.example.com")
.setBasePath("/v1")
.addHeader("Content-Type",
"application/json")
.addHeader("Authorization",
"Bearer " + token)
.setRelaxedHTTPSValidation()
.build();
// Use in test:
given().spec(spec)
.when().get("/users")
.then().statusCode(200);import io.restassured.builder
.ResponseSpecBuilder;
ResponseSpecification resSpec =
new ResponseSpecBuilder()
.expectStatusCode(200)
.expectContentType(ContentType.JSON)
.expectResponseTime(
lessThan(2000L),
TimeUnit.MILLISECONDS)
.build();
// Use in test:
given().spec(spec)
.when().get("/users")
.then().spec(resSpec);// Simple GET
given()
.when().get("https://api.example.com/users")
.then().statusCode(200);
// Query params: /users?page=1&size=10
given()
.queryParam("page", 1)
.queryParam("size", 10)
.when().get("/users")
.then().statusCode(200);
// Path param: /users/42
given()
.pathParam("id", 42)
.when().get("/users/{id}")
.then().statusCode(200);given()
.header("Authorization","Bearer abc")
.header("Accept","application/json")
.headers("X-Custom","v1","X-Req","id")
.cookie("session", "xyz123")
.contentType(ContentType.JSON)
.when().get("/profile")
.then().statusCode(200);String body =
"{ \"name\": \"Alice\","
+ " \"email\": \"a@b.com\" }";
given()
.contentType(ContentType.JSON)
.body(body)
.when().post("/users")
.then().statusCode(201);// HashMap (Jackson auto-serializes)
Map<String,Object> map = new HashMap<>();
map.put("name", "Alice");
map.put("age", 30);
// POJO (needs getters/setters)
User user = new User("Alice", 30);
given().contentType(ContentType.JSON)
.body(user)
.when().post("/users")
.then().statusCode(201);// PUT โ replace entire resource
given()
.contentType(ContentType.JSON)
.pathParam("id", 42)
.body("{ \"name\": \"Bob\","
+ " \"email\": \"b@c.com\" }")
.when().put("/users/{id}")
.then().statusCode(200);
// PATCH โ update only given fields
given()
.contentType(ContentType.JSON)
.pathParam("id", 42)
.body("{ \"name\": \"Bob\" }")
.when().patch("/users/{id}")
.then().statusCode(200);// DELETE
given()
.pathParam("id", 42)
.when().delete("/users/{id}")
.then().statusCode(204);
// HEAD โ headers only, no body
given()
.when().head("/users")
.then().statusCode(200)
.header("Content-Type",
containsString("json"));given()
.contentType(
"application/x-www-form-urlencoded")
.formParam("username", "admin")
.formParam("password", "pass123")
.when().post("/login")
.then().statusCode(200);given()
.multiPart("file", new File(
"src/test/resources/doc.pdf"))
.multiPart("description",
"My document")
.when().post("/upload")
.then().statusCode(201);then().statusCode(200);
then().statusCode(
anyOf(is(200), is(201)));
then().statusLine("HTTP/1.1 200 OK");
then().statusLine(
containsString("OK"));
// Response time under 2 seconds
then().time(
lessThan(2000L),
TimeUnit.MILLISECONDS);then()
.header("Content-Type",
containsString("application/json"))
.header("Cache-Control",
notNullValue())
.header("X-Rate-Limit",
equalTo("100"))
.cookie("sessionId",
notNullValue())
.cookie("token", "abc123");then().body(
"name",
equalTo("Alice"),
"age",
greaterThan(18),
"email",
containsString("@"),
"status",
not(emptyString()),
"address.city",
equalTo("Delhi"),
"roles",
hasItems("admin", "user"),
"roles.size()",
greaterThanOrEqualTo(1),
"data",
hasSize(10),
"score",
closeTo(9.5, 0.5),
"active",
is(true)
);Response res =
given().get("/users/1");
// Single values
String name = res.jsonPath()
.getString("name");
int age = res.jsonPath()
.getInt("age");
boolean ok = res.jsonPath()
.getBoolean("active");
// Nested object field
String city = res.jsonPath()
.getString("address.city");
// List from JSON array
List<String> roles = res.jsonPath()
.getList("roles");// All names from array
List<String> names = res.jsonPath()
.getList("data.name");
// Find object where id == 5
String n = res.jsonPath().getString(
"data.find{it.id==5}.name");// Store entire response object
Response res =
given().get("/users/1")
.andReturn();
// Extract from fluent chain
String token =
given()
.body(creds)
.post("/login")
.then().statusCode(200)
.extract().path("data.token");
// Body as String / POJO / header
String body = res.getBody()
.asString();
User user = res.as(User.class);
String hdr = res.getHeader(
"X-Token");// Basic Auth (waits for 401 challenge)
given().auth()
.basic("user", "pass")
// Preemptive Basic (no challenge wait)
given().auth()
.preemptive()
.basic("user", "pass")
// Bearer Token via header
given().header("Authorization",
"Bearer " + accessToken)
// OAuth 2.0
given().auth()
.oauth2(accessToken)
// API Key as query param
given().queryParam("api_key", key)
// Digest Auth
given().auth()
.digest("user", "pass")// Log full request
given().log().all()
// Log specific parts of request
given().log().headers()
given().log().body()
given().log().params()
given().log().uri()
// Log full response
.then().log().all()
.then().log().body()
.then().log().status()
.then().log().headers()
// โ
Best practice: only log on failure
given().log().ifValidationFails()
.when().get("/users")
.then().log().ifValidationFails()
.statusCode(200);import static io.restassured.module.jsv
.JsonSchemaValidator.*;
// Schema file:
// src/test/resources/schemas/user.json
given()
.when().get("/users/1")
.then().statusCode(200)
.body(matchesJsonSchemaInClasspath(
"schemas/user.json"));{
"type": "object",
"properties": {
"id": { "type": "integer" },
"name": { "type": "string" },
"email": { "type": "string" }
},
"required": ["id","name","email"]
}import io.restassured.filter.log
.RequestLoggingFilter;
import io.restassured.filter.log
.ResponseLoggingFilter;
// Add built-in filters
given()
.filter(new RequestLoggingFilter())
.filter(new ResponseLoggingFilter())
.when().get("/users");
// Custom filter (add timestamp header)
given().filter((req, res, ctx) -> {
req.header("X-Time",
String.valueOf(
System.currentTimeMillis()));
return ctx.next(req, res);
}).when().get("/users");import org.testng.annotations.*;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import io.restassured.http.ContentType;
public class UserApiTest {
@BeforeSuite
public void globalSetup() {
RestAssured.baseURI =
"https://api.example.com";
RestAssured.basePath = "/v1";
}
@BeforeClass
public void login() {
// extract token here
}
@Test
public void getUser() {
given()
.pathParam("id", 1)
.when().get("/users/{id}")
.then()
.statusCode(200)
.body("name", notNullValue());
}
@AfterSuite
public void teardown() {
RestAssured.reset();
}
}// Step 1: Login, extract token
String token =
given()
.contentType(ContentType.JSON)
.body("{ \"username\":\"admin\","
+ " \"password\":\"pass\" }")
.when().post("/auth/login")
.then().statusCode(200)
.extract().path("data.token");
// Step 2: Use token in secured request
given()
.header("Authorization",
"Bearer " + token)
.when().get("/dashboard")
.then().statusCode(200);
// Step 3: Use extracted ID in next call
int id =
given().get("/users/me")
.then().extract().path("id");
given()
.pathParam("id", id)
.when().get("/orders/{id}")
.then().statusCode(200);@DataProvider(name = "users")
public Object[][] data() {
return new Object[][] {
{"Alice","a@x.com", 201},
{"Bob", "b@x.com", 201},
{"", "bad", 400}
};
}
@Test(dataProvider = "users")
public void testCreate(
String name,
String email,
int expected) {
given()
.contentType(ContentType.JSON)
.body("{ \"name\":\"" + name
+ "\",\"email\":\""+ email
+ "\" }")
.when().post("/users")
.then().statusCode(expected);
}// pom: assertj-core
import org.assertj.core.api.SoftAssertions;
Response res =
given().get("/users/1");
SoftAssertions soft =
new SoftAssertions();
soft.assertThat(res.statusCode())
.isEqualTo(200);
soft.assertThat(
res.jsonPath().getString("name"))
.isNotBlank();
soft.assertThat(
res.jsonPath().getInt("age"))
.isGreaterThan(0);
soft.assertAll(); // runs all at oncethen().body(
"$", hasSize(10),
"[0].name", equalTo("Alice"),
"name", hasItems("Alice","Bob"),
"age", everyItem(greaterThan(0)),
"status",
everyItem(equalTo("active")));// Define POJO (Jackson needs
// no-arg constructor + getters/setters)
public class User {
private String name;
private int age;
private String email;
public User() {}
public User(String name, int age) {
this.name = name;
this.age = age;
}
// + getters and setters
}// Serialize: POJO โ JSON โ POST
User newUser = new User("Alice", 30);
given()
.contentType(ContentType.JSON)
.body(newUser)
.when().post("/users")
.then().statusCode(201);
// Deserialize: GET โ JSON โ POJO
User user =
given().get("/users/1")
.then().statusCode(200)
.extract().as(User.class);
System.out.println(user.getName());// Request XML response
Response res =
given()
.accept(ContentType.XML)
.when().get("/users/1");
// Assert via XPath in then()
res.then().body(
"user.name",
equalTo("Alice"),
"user.address.city",
equalTo("Delhi")
);
// Extract via XmlPath
String city = res.xmlPath()
.getString("user.address.city");// Route all requests via proxy
given()
.proxy("localhost", 8888)
.when().get("/users")
.then().statusCode(200);
// Globally skip SSL (e.g. staging)
RestAssured
.useRelaxedHTTPSValidation();
// Per-request SSL skip
given()
.relaxedHTTPSValidation()
.when().get("https://staging.api.com")
.then().statusCode(200);@Test
public void crudFlowTest() {
// โโ CREATE โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
int userId =
given()
.contentType(ContentType.JSON)
.body("{ \"name\":\"Alice\", \"email\":\"a@x.com\" }")
.when().post("/users")
.then()
.statusCode(201)
.body("name", equalTo("Alice"))
.extract().path("id");
// โโ READ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
given()
.pathParam("id", userId)
.when().get("/users/{id}")
.then()
.statusCode(200)
.body("name", equalTo("Alice"))
.body("email", equalTo("a@x.com"));
// โโ UPDATE (PUT) โโโโโโโโโโโโโโโโโโโโโโโโโโโ
given()
.contentType(ContentType.JSON)
.pathParam("id", userId)
.body("{ \"name\":\"Bob\", \"email\":\"b@x.com\" }")
.when().put("/users/{id}")
.then()
.statusCode(200)
.body("name", equalTo("Bob"));
// โโ DELETE โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
given()
.pathParam("id", userId)
.when().delete("/users/{id}")
.then().statusCode(204);
// โโ VERIFY DELETED (404) โโโโโโโโโโโโโโโโโโ
given()
.pathParam("id", userId)
.when().get("/users/{id}")
.then().statusCode(404);
}