Answer
Validate Response Headers in Rest Assured
Method 1: Extract and Validate Programmatically
Java
import io.restassured.RestAssured;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.response.Response;
public class HeaderValidationTest {
public static void main(String[] args) {
// Set the base URI
RestAssured.baseURI = "https://api.example.com";
// Send a GET request to the endpoint
Response response = RestAssured.get("/endpoint");
// Extract headers from the response
Headers headers = response.getHeaders();
// Validate Content-Type Header
Header contentType = headers.get("Content-Type");
if (contentType != null) {
assert contentType.getValue().equals("application/json")
: "Content-Type is not application/json";
} else {
throw new AssertionError("Content-Type header is missing");
}
// Validate Custom Header
Header customHeader = headers.get("X-Custom-Header");
if (customHeader != null) {
assert customHeader.getValue().equals("ExpectedValue")
: "X-Custom-Header does not have the expected value";
} else {
throw new AssertionError("X-Custom-Header is missing");
}
System.out.println("All headers are valid");
}
}
Method 2: BDD Style Header Assertions
Java
given()
.when()
.get("https://api.example.com/users")
.then()
.statusCode(200)
.header("Content-Type", containsString("application/json"))
.header("X-Rate-Limit", notNullValue())
.header("Cache-Control", equalTo("no-cache"));
Method 3: Print All Response Headers
Java
Response response = given().when().get("/api/users");
// Print all headers
response.getHeaders().forEach(header -> {
System.out.println(header.getName() + ": " + header.getValue());
});
Header Validation Steps
- ✓Extract response headers with
response.getHeaders() - ✓Get specific header with
headers.get("Header-Name") - ✓Check presence — if
null, throw assertion error - ✓Validate value — compare with expected using
getValue().equals(...)
Common Response Headers to Validate
| Header | Expected Value |
|---|---|
Content-Type | application/json |
Cache-Control | no-cache or max-age=3600 |
Authorization | Token present |
X-Rate-Limit-Remaining | Number > 0 |
