How to Verify JSON Response Headers in Rest Assured?

 When working with RESTful web services, verifying response headers is an essential part of testing API endpoints. Headers often provide critical metadata about the response, including content type, encoding, caching directives, or server-specific information. In this blog post, we’ll learn how to verify JSON response headers using Rest Assured, a popular Java library for API testing.


Why Verify Response Headers?

Validating response headers ensures:

  1. Compliance: APIs follow proper standards and return expected headers (e.g., Content-Type should match the format of the body).
  2. Security: Headers like CORS, Authorization, and Content-Security-Policy should be correctly set.
  3. Performance: Headers like Cache-Control or ETag influence caching and reduce redundant API calls.

Setting Up Rest Assured

To start, ensure you’ve added the Rest Assured dependency in your pom.xml:

<dependency>

    <groupId>io.rest-assured</groupId>

    <artifactId>rest-assured</artifactId>

    <version>5.3.0</version>

    <scope>test</scope>

</dependency>

Sample API Response

Let’s consider a sample JSON API endpoint:
GET https://jsonplaceholder.typicode.com/posts/1

Sample JSON Response:

{
    "userId": 1,
    "id": 1,
    "title": "Sample Post",
    "body": "This is a sample blog post."
}

Sample Response Headers:

Content-Type: application/json; charset=utf-8
Cache-Control: public, max-age=3600
ETag: W/"12345"

Verifying JSON Response Headers

Here’s how you can validate specific response headers using Rest Assured:

Basic Header Validation

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class HeaderValidationTest {
    public static void main(String[] args) {
        baseURI = "https://jsonplaceholder.typicode.com";

        given()
            .when()
                .get("/posts/1")
            .then()
                .assertThat()
                .statusCode(200) // Verify status code
                .header("Content-Type", "application/json; charset=utf-8") // Validate Content-Type
                .header("Cache-Control", containsString("public")) // Validate part of the Cache-Control header
                .header("ETag", notNullValue()); // Ensure ETag is present
    }
}

Extracting and Validating Headers

If you need to perform more advanced validations or reuse header values, you can extract headers using the Response object:

import io.restassured.response.Response;

import static io.restassured.RestAssured.*;


public class ExtractHeaderTest {

    public static void main(String[] args) {

        baseURI = "https://jsonplaceholder.typicode.com";


        Response response = given()

                                .when()

                                    .get("/posts/1");


        // Extract and print headers

        String contentType = response.getHeader("Content-Type");

        String cacheControl = response.getHeader("Cache-Control");


        System.out.println("Content-Type: " + contentType);

        System.out.println("Cache-Control: " + cacheControl);


        // Perform validations

        assert contentType.equals("application/json; charset=utf-8");

        assert cacheControl.contains("public");

    }

}

Advanced Header Assertions

Validate All Headers

You can validate multiple headers at once using the headers() method:

import static io.restassured.RestAssured.*;

import static org.hamcrest.Matchers.*;


public class MultipleHeadersValidationTest {

    public static void main(String[] args) {

        baseURI = "https://jsonplaceholder.typicode.com";


        given()

            .when()

                .get("/posts/1")

            .then()

                .assertThat()

                .headers("Content-Type", "application/json; charset=utf-8",

                         "Cache-Control", containsString("public"),

                         "ETag", notNullValue());

    }

}

Use Hamcrest Matchers

Rest Assured supports Hamcrest matchers for more complex validations. For example:

given()
    .when()
        .get("/posts/1")
    .then()
        .header("Content-Type", equalToIgnoringCase("application/json; charset=utf-8"))
        .header("Cache-Control", startsWith("public"))
        .header("ETag", matchesPattern("^W/\"[0-9]+\"$"));

Followers