</>

Technology

Rest Assured

Difficulty

Beginner

Interview Question

How to pass headers in a GET request using Rest Assured?

Answer

Passing Headers in Rest Assured

HTTP headers carry metadata about the request — Content-Type, Authorization, Accept, custom headers, etc.

Single Header

Java
@Test
public void validateGivenHeader() {

    Response resp = given()
                        .header("Content-Type", "application/json")
                        .when()
                        .get("https://gorest.co.in/public-api/users");

    assertEquals(resp.getStatusCode(), 200);
    System.out.println(resp.getBody().asString());
}

Multiple Headers

Java
@Test
public void multipleHeaders() {

    Response resp = given()
                        .header("Content-Type", "application/json")
                        .header("Accept", "application/json")
                        .header("Authorization", "Bearer your-token-here")
                        .when()
                        .get("https://api.example.com/users");

    assertEquals(resp.getStatusCode(), 200);
}

Using Headers Object

Java
@Test
public void headersObject() {

    Headers headers = new Headers(
        new Header("Content-Type", "application/json"),
        new Header("Authorization", "Bearer token123")
    );

    given()
        .headers(headers)
        .when()
        .get("https://api.example.com/users")
        .then()
        .statusCode(200);
}

Validate Response Headers

Java
@Test
public void validateResponseHeaders() {

    Response response = RestAssured.get("/endpoint");
    Headers headers = response.getHeaders();

    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");
    }
}

Common Headers

HeaderPurpose
Content-TypeFormat of the request body
AcceptExpected response format
AuthorizationBearer token / API key
X-API-KeyCustom API key

Follow AutomateQA

Related Topics