RA

REST Assured Cheat Sheet

API TESTING WITH JAVA ยท QUICK REFERENCE GUIDE

๐ŸŽ“ Next Gen QA IT Coaching Classes
๐Ÿ“ž Mr. Khan Sir  |  8700350994
CBSE/ICSE B.Tech / BCA / MCA Polytechnic Online & Offline API Testing
Maven / Gradle Setup ยท Base URI Config ยท Static Imports ยท Request & Response Specifications
Maven Dependency (pom.xml)
REST Assured + TestNG + Jackson + JSON Schema Validator
<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>
Static Imports (Required)
Add at the top of every test class
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;
Base URI / Global Config
Set once in @BeforeClass or @BeforeSuite
RestAssured.baseURI = "https://api.example.com"; RestAssured.basePath = "/v1"; RestAssured.port = 8080; // Skip SSL certificate validation RestAssured.useRelaxedHTTPSValidation(); // Reset all global config RestAssured.reset();
Request Specification (Reusable)
Build once, reuse across all tests
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);
Response Specification (Reusable)
Define expected response shape once
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);
HTTP Methods ยท GET ยท POST ยท PUT ยท PATCH ยท DELETE ยท Headers ยท Query & Path Params ยท Form / Multipart
GET Request
Simple GET / query param / path param
// 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);
Headers & Cookies
Single / multiple headers / cookie
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);
POST Request
POST with JSON String body
String body = "{ \"name\": \"Alice\"," + " \"email\": \"a@b.com\" }"; given() .contentType(ContentType.JSON) .body(body) .when().post("/users") .then().statusCode(201);
POST with HashMap / POJO body
// 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 & PATCH Request
PUT (full update) / PATCH (partial update)
// 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 & HEAD Request
DELETE by id / HEAD for headers only
// 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"));
Form Data & Multipart Upload
Form URL-encoded (login forms)
given() .contentType( "application/x-www-form-urlencoded") .formParam("username", "admin") .formParam("password", "pass123") .when().post("/login") .then().statusCode(200);
Multipart file upload
given() .multiPart("file", new File( "src/test/resources/doc.pdf")) .multiPart("description", "My document") .when().post("/upload") .then().statusCode(201);
Status Code ยท Hamcrest Body Assertions ยท Header & Cookie Assertions ยท JSONPath Extraction ยท Extract Response
Status Code & Time Assertions
Exact / multiple codes / status line / time
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);
Header & Cookie Assertions
Assert response headers and cookies exist / match
then() .header("Content-Type", containsString("application/json")) .header("Cache-Control", notNullValue()) .header("X-Rate-Limit", equalTo("100")) .cookie("sessionId", notNullValue()) .cookie("token", "abc123");
Body Assertions โ€“ Hamcrest Matchers
Fields / types / nested / arrays / numeric
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) );
JSONPath Extraction
Extract single value / nested field / list
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");
Filter / find from array of objects
// 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");
Extract & Store Response
Store response / extract value from chain
// 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");
Authentication ยท Logging ยท JSON Schema Validation ยท XML Path ยท Filters (Request/Response Interceptors)
Authentication Types
Basic / Preemptive / Bearer / OAuth2 / API Key
// 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")
Logging
Log request / response / on failure (best practice)
// 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);
JSON Schema Validation
Validate response against a JSON schema file
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"));
Sample user.json schema
{ "type": "object", "properties": { "id": { "type": "integer" }, "name": { "type": "string" }, "email": { "type": "string" } }, "required": ["id","name","email"] }
Filters (Interceptors)
Built-in logging filters / custom filter
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");
TestNG Integration ยท POJO Deserialization ยท Request Chaining ยท Data-Driven ยท Soft Assertions ยท List Assertions
TestNG Integration
Full test class structure with lifecycle hooks
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(); } }
Request Chaining (Token Flow)
Login โ†’ extract token โ†’ use in next request
// 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);
Data-Driven with @DataProvider
Run same test with multiple inputs
@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); }
Soft Assertions & List Assertions
AssertJ soft assertions โ€“ collect all failures
// 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 once
Assert arrays / every item / nested
then().body( "$", hasSize(10), "[0].name", equalTo("Alice"), "name", hasItems("Alice","Bob"), "age", everyItem(greaterThan(0)), "status", everyItem(equalTo("active")));
POJO Serialization / Deserialization ยท Proxy & SSL ยท XML Path ยท Complete CRUD End-to-End Test
POJO Serialization & Deserialization
Java POJO class (Jackson)
// 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 (POST) / Deserialize (GET)
// 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());
XML Path (For XML APIs)
Parse and assert XML response body
// 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");
Proxy & SSL Config
Route via proxy / disable SSL
// 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);
Complete End-to-End CRUD Test
Create โ†’ Read โ†’ Update โ†’ Delete โ€“ full lifecycle in one @Test
@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); }