π Core HTTP GET Foundations & Wire Validation in Java
The GET HTTP verb is the foundational building block of RESTful web services, representing safe, idempotent read operations. While initiating a simple network call in Java requires only a target URL, writing production-grade automated assertions requires systematically validating the entire wire response envelope. In REST Assured, the Given-When-Then BDD workflow enables automation engineers to configure prerequisites (headers, query parameters, authorization tokens), trigger the HTTP GET action, and immediately assert response criteriaβsuch as verifying the HTTP status code (200 OK), validating transport headers (Content-Type, Cache-Control, ETag), evaluating latency SLA bounds, and testing exact body values via Hamcrest matchersβwithout writing brittle parsing boilerplate.
HTTP GET WIRE TRANSACTION & VALIDATION ENVELOPE:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β OUTBOUND CLIENT REQUEST (Given Phase) β
β GET /v1/students/STU-88219 HTTP/1.1 β
β Host: staging-api.nikita-infotech.com β
β Accept: application/json β
β X-Request-ID: req_8f9b10c9-bf12 β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Dispatched over TCP / TLS Socket)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β INBOUND SERVER RESPONSE (Evaluated in Then Phase) β
β β
β βββ 1. STATUS LINE VALIDATION: β
β β β’ Protocol: HTTP/1.1 β
β β β’ Status Code: 200 βββΊ .statusCode(200) β
β β β’ Reason Phrase: OK βββΊ .statusLine(containsString) β
β β β
β βββ 2. RESPONSE HEADERS VALIDATION: β
β β β’ Content-Type: application/json; charset=utf-8 βββΊ .contentType(...) β
β β β’ Cache-Control: no-cache, no-store βββΊ .header("Cache-Control", ..)β
β β β’ ETag: W/"student-88219-hash" βββΊ .header("ETag", notNullValueβ
β β β
β βββ 3. LATENCY & TRANSPORT TIMING: β
β β β’ Elapsed Wire Time: 142 ms βββΊ .time(lessThan(1000L)) β
β β β
β βββ 4. ENTITY BODY ATTRIBUTES (Hamcrest Assertions): β
β β’ status: "SUCCESS" βββΊ .body("status", equalTo(..))β
β β’ data.id: "STU-88219" βββΊ .body("data.id", startsWith)β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
package com.nikita.restassured.basics;
import org.testng.annotations.Test;
// 1. Mandatory static imports for clean BDD DSL
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class FirstGetRequestTest {
@Test(description = "Verify public health check endpoint returns 200 OK and status UP")
public void testPublicHealthEndpoint() {
given()
.baseUri("https://staging-api.nikita-infotech.com")
.basePath("/v1")
.when()
.get("/health")
.then()
.statusCode(200)
.body("status", equalTo("UP"));
System.out.println("[β] Minimalist GET request executed and verified successfully.");
}
}
is(), equalTo()), and checking the HTTP protocol reason phrase.
package com.nikita.restassured.basics;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class StatusCodeValidationTest {
@Test(description = "Demonstrate multiple techniques for asserting status codes and lines")
public void testStatusValidations() {
given()
.baseUri("https://staging-api.nikita-infotech.com/v1")
.when()
.get("/students")
.then()
// Technique A: Direct integer assertion
.statusCode(200)
// Technique B: Hamcrest matcher assertion
.statusCode(is(equalTo(200)))
// Technique C: Assert status code is in successful 2xx range
.statusCode(allOf(greaterThanOrEqualTo(200), lessThan(300)))
// Technique D: Assert full HTTP protocol status line
.statusLine("HTTP/1.1 200 OK")
// Technique E: Partial match on status line reason phrase
.statusLine(containsString("OK"));
System.out.println("[β] Status code (200) and status line verified across all assertion patterns.");
}
}
ContentType.JSON, checks Cache-Control directives, validates dynamic correlation IDs, and asserts header existence with notNullValue().
package com.nikita.restassured.basics;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class HeaderValidationTest {
@Test(description = "Verify Content-Type, security headers, and gateway correlation IDs")
public void testHeaderAssertions() {
given()
.baseUri("https://staging-api.nikita-infotech.com/v1")
.header("Accept", "application/json")
.when()
.get("/students/STU-88219")
.then()
.statusCode(200)
// 1. Validate MIME Content-Type using enum
.contentType(ContentType.JSON)
// 2. Validate exact Content-Type string including charset
.header("Content-Type", equalTo("application/json; charset=utf-8"))
// 3. Validate Caching Directives
.header("Cache-Control", containsString("no-cache"))
// 4. Assert header existence and pattern
.header("X-Correlation-ID", notNullValue())
.header("X-Correlation-ID", matchesPattern("^[0-9a-f-]{36}$"))
// 5. Assert Server header contains expected gateway software
.header("Server", containsString("nginx"));
System.out.println("[β] Response headers satisfied all security and content type requirements.");
}
}
time() in milliseconds and seconds to enforce API performance SLA compliance.
package com.nikita.restassured.basics;
import org.testng.annotations.Test;
import java.util.concurrent.TimeUnit;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.lessThan;
public class LatencySlaValidationTest {
@Test(description = "Assert response latency complies with 800ms SLA ceiling")
public void testResponseTimeSla() {
given()
.baseUri("https://staging-api.nikita-infotech.com/v1")
.when()
.get("/students")
.then()
.statusCode(200)
// Pattern A: Evaluate latency in milliseconds (Long)
.time(lessThan(800L))
// Pattern B: Evaluate latency using explicit TimeUnit (Seconds)
.time(lessThan(2L), TimeUnit.SECONDS);
System.out.println("[β] Gateway latency satisfied the 800ms SLA ceiling.");
}
}
body("path", matcher).
package com.nikita.restassured.basics;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class BasicBodyValidationTest {
@Test(description = "Verify core body attributes using Hamcrest matchers")
public void testBodyAttributes() {
given()
.baseUri("https://staging-api.nikita-infotech.com/v1")
.when()
.get("/students/STU-88219")
.then()
.statusCode(200)
// 1. String exact and partial validations
.body("status", equalTo("SUCCESS"))
.body("data.id", equalTo("STU-88219"))
.body("data.fullName", containsString("Nikita"))
// 2. Numeric boundary comparisons
.body("data.enrolledCredits", greaterThanOrEqualTo(1))
.body("data.enrolledCredits", lessThanOrEqualTo(20))
.body("data.enrolledCredits", is(4))
// 3. Boolean state assertion
.body("data.isActive", is(true))
// 4. Nullability check
.body("data.email", notNullValue())
.body("data.graduationDate", nullValue());
System.out.println("[β] Response body attributes satisfied all data contract assertions.");
}
}
.extract().response() and .extract().path() for logging, downstream request chaining, or external test assertions.
package com.nikita.restassured.basics;
import io.restassured.response.Response;
import org.testng.Assert;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class ResponseExtractionTest {
@Test(description = "Extract primitive values and Response object from BDD pipeline")
public void testExtractResponseData() {
// =====================================================================
// TECHNIQUE A: DIRECT PATH EXTRACTION INTO A PRIMITIVE STRING
// =====================================================================
String extractedEmail = given()
.baseUri("https://staging-api.nikita-infotech.com/v1")
.when()
.get("/students/STU-88219")
.then()
.statusCode(200)
.extract()
.path("data.email");
System.out.println("[+] Extracted Email directly: " + extractedEmail);
Assert.assertEquals(extractedEmail, "nikita.sharma@nikita-infotech.com");
// =====================================================================
// TECHNIQUE B: EXTRACT FULL RESPONSE OBJECT FOR MULTI-PROPERTY ACCESS
// =====================================================================
Response fullResponse = given()
.baseUri("https://staging-api.nikita-infotech.com/v1")
.when()
.get("/students/STU-88219")
.then()
.statusCode(200)
.body("status", equalTo("SUCCESS"))
.extract()
.response();
// Read multiple properties without repeating network calls
int statusCode = fullResponse.getStatusCode();
String contentType = fullResponse.getHeader("Content-Type");
int credits = fullResponse.path("data.enrolledCredits");
long latencyMs = fullResponse.getTime();
System.out.println("[+] Status Code: " + statusCode
+ " | Content-Type: " + contentType
+ " | Credits: " + credits
+ " | Latency: " + latencyMs + "ms");
}
}
log().all(), log().headers(), log().body(), and log().ifValidationFails() for debugging test execution.
package com.nikita.restassured.basics;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class WireLoggingTest {
@Test(description = "Demonstrate selective wire logging during test execution")
public void testWireLoggingOptions() {
given()
.baseUri("https://staging-api.nikita-infotech.com/v1")
.header("X-Debug-Mode", "true")
// Log only outbound request parameters and headers
.log().parameters()
.log().headers()
.when()
.get("/students/STU-88219")
.then()
// Log full response body to console
.log().body()
.statusCode(200)
.body("status", equalTo("SUCCESS"));
System.out.println("[β] Wire traffic selectively printed to console.");
}
@Test(description = "Production CI logging pattern: stays silent unless test fails")
public void testCiFailOnlyLogging() {
given()
.baseUri("https://staging-api.nikita-infotech.com/v1")
.log().ifValidationFails() // Logs outbound request only on failure
.when()
.get("/students/STU-88219")
.then()
.log().ifValidationFails() // Logs inbound response only on failure
.statusCode(200)
.body("status", equalTo("SUCCESS"));
System.out.println("[β] Silent validation passed; zero clutter printed to build logs.");
}
}
HTTP 404 Not Found) and asserts that the returned error envelope satisfies RFC 7807 problem details standards.
package com.nikita.restassured.basics;
import io.restassured.http.ContentType;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class NegativeGetRequestTest {
@Test(description = "Verify querying a non-existent student returns 404 with standard error body")
public void testNonExistentStudentReturns404() {
String invalidStudentId = "STU-99999999";
given()
.baseUri("https://staging-api.nikita-infotech.com/v1")
.pathParam("studentId", invalidStudentId)
.log().ifValidationFails()
.when()
.get("/students/{studentId}")
.then()
.log().ifValidationFails()
// 1. Verify 404 Not Found status
.statusCode(404)
.statusLine(containsString("Not Found"))
// 2. Verify error Content-Type (RFC 7807 problem+json or standard json)
.contentType(containsString("json"))
// 3. Verify structured error envelope attributes
.body("title", equalTo("Resource Not Found"))
.body("status", equalTo(404))
.body("detail", containsString("Student with ID '" + invalidStudentId + "' was not found"))
.body("timestamp", notNullValue());
System.out.println("[β] Negative GET scenario validated: 404 Not Found returned with compliant error envelope.");
}
}
REST ASSURED GET VALIDATIONS SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββ
β VALIDATION TARGET β REST ASSURED METHOD β HAMCREST MATCHER β PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββββ€
β Status Code (Integer) β .statusCode(200) β is(equalTo(200)) β Transport protocol success β
β Status Code Range β .statusCode(matcher) β allOf(>=200, <300)Validates 2xx success range β
β Status Line β .statusLine(textOrMatcher) β containsString β Protocol + Reason phrase check β
β Content-Type Enum β .contentType(ContentType.JSON)Enum Binding β Asserts MIME type representationβ
β Content-Type String β .header("Content-Type", ..) β equalTo(..) β Exact match including charset β
β Custom Transport Header β .header("X-Correlation-ID") β notNullValue() β Distributed tracing audit β
β Latency SLA Ceiling β .time(matcher, [TimeUnit]) β lessThan(800L) β Enforces response time budget β
β Field Exact Match β .body("data.id", matcher) β equalTo("STU-1") β Exact property verification β
β String Pattern Match β .body("data.code", matcher) β matchesPattern() β Regex syntax validation β
β Numeric Boundary Check β .body("data.credits", m) β greaterThan(0) β Numeric range verification β
β Boolean State Check β .body("data.active", matcher)β is(true) β State flag verification β
β Field Nullability β .body("data.notes", matcher) β nullValue() β Asserts optional/null field β
β Extract Single Value β .extract().path("data.id") β N/A (Extraction) β Captures value for chaining β
β Extract Full Response β .extract().response() β N/A (Extraction) β Returns raw Response instance β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββ€
β TOP 5 GET VALIDATION BEST PRACTICES: β
β 1. Validate status and Content-Type first: Guard against analyzing body payloads on transport errors. β
β 2. Set SLA thresholds with .time(): Catch performance regressions before they reach production. β
β 3. Use log().ifValidationFails(): Keep CI logs clean while capturing full packet dumps on failures. β
β 4. Test negative scenarios thoroughly: Verify 404, 401, and 403 error envelopes match standards. β
β 5. Extract values cleanly with .extract().path(): Transition out of BDD chains to capture IDs/tokens. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ