</>

Technology

Rest Assured

Difficulty

Intermediate

Interview Question

How to validate headers in API response using Rest Assured?

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

  1. Extract response headers with response.getHeaders()
  2. Get specific header with headers.get("Header-Name")
  3. Check presence — if null, throw assertion error
  4. Validate value — compare with expected using getValue().equals(...)

Common Response Headers to Validate

HeaderExpected Value
Content-Typeapplication/json
Cache-Controlno-cache or max-age=3600
AuthorizationToken present
X-Rate-Limit-RemainingNumber > 0

Follow AutomateQA

Related Topics