How to Test a Single Response Header by Rest Assured

 

To test a single response header in a GET API using Rest Assured in Java, you can follow these steps:


We want to:

  • Send a GET request to https://reqres.in/api/users?page=2

  • Extract and validate a specific response header (example: Content-Type)



What is a Response Header?

response header provides metadata about the server response. Common headers include:

  • Content-Type

  • Content-Encoding

  • Date

  • Server

  • Connection



Steps in Rest Assured

  • Set the base URI
  • Send a GET request
  • Extract the specific header
  • Validate it using assertion



Sample Java Code Using Rest Assured


import io.restassured.RestAssured;
import io.restassured.response.Response;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

public class GetResponseHeaderTest {

    public static void main(String[] args) {
        
        // Step 1: Set base URI
        RestAssured.baseURI = "https://reqres.in";

        // Step 2: Send GET request and get response
        Response response = RestAssured
                .given()
                .when()
                .get("/api/users?page=2")
                .then()
                .extract()
                .response();

        // Step 3: Print and verify a single header, e.g. Content-Type
        String contentType = response.getHeader("Content-Type");
        System.out.println("Content-Type header is: " + contentType);

        // Step 4: Assert the header
        assertThat("Header validation failed", contentType, equalTo("application/json; charset=utf-8"));
    }
}





Explanation:

  • getHeader("Content-Type") fetches the value of the specified header.
  • assertThat(..., equalTo(...)) checks if the header value is as expected.




Maven Dependency:


<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>5.4.0</version>
    <scope>test</scope>
</dependency>

No comments:

Post a Comment