Introduction

In our previous post, we explored Request Body (JSON, XML) in REST Assured, learning how to send data in API requests. Now, we’ll dive into Headers and Cookies, which are essential for customizing and authenticating API requests. This guide is designed for beginners and experienced developers, providing clear explanations and practical examples to help you master headers and cookies in REST Assured.

Key Point: Headers and cookies allow you to send metadata and session information with API requests, enabling authentication, content specification, and more.

What Are Headers and Cookies?

Headers are key-value pairs sent in the HTTP request to provide metadata, such as the content type, authentication tokens, or custom parameters. For example, Content-Type: application/json specifies the request body format.

Cookies are key-value pairs used to maintain session state or store user-specific data, often for authentication or tracking. They are typically sent in the Cookie header.

REST Assured simplifies adding headers and cookies using methods like header(), headers(), and cookie(), making it easy to customize requests.

Adding Headers in REST Assured

Headers are added using the header() or headers() methods in the given() block. Let’s explore with examples using the public API https://jsonplaceholder.typicode.com.

Option 1: Adding a Single Header

Use the header() method to add a single header to a request.


import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class SingleHeaderTest {

    @Test
    public void testSingleHeader() {
        RestAssured.baseURI = "https://jsonplaceholder.typicode.com";

        given()
            .header("Content-Type", "application/json")
            .when()
                .get("/posts")
            .then()
                .statusCode(200)
                .body("[0].id", notNullValue());
    }
}

Explanation:

  • header("Content-Type", "application/json"): Adds the Content-Type header to specify the request or response format.
  • get("/posts"): Sends a GET request with the header.
  • then(): Validates the response status and content.
Important: Common headers like Content-Type, Authorization, and Accept are critical for API interactions. Check the API documentation for required headers.

Option 2: Adding Multiple Headers

Use the headers() method to add multiple headers at once.


import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class MultipleHeadersTest {

    @Test
    public void testMultipleHeaders() {
        RestAssured.baseURI = "https://jsonplaceholder.typicode.com";

        given()
            .headers(
                "Content-Type", "application/json",
                "Accept", "application/json",
                "Custom-Header", "TestValue"
            )
            .when()
                .get("/posts")
            .then()
                .statusCode(200)
                .body("[0].userId", notNullValue());
    }
}

Explanation:

  • headers(): Accepts key-value pairs for multiple headers, such as Content-Type, Accept (specifying the expected response format), and a custom header.
  • This approach is concise and ideal for multiple headers.

Adding Cookies in REST Assured

Cookies are added using the cookie() or cookies() methods. Cookies are often used for session management or authentication.

Option 1: Adding a Single Cookie

Use the cookie() method to add a single cookie to a request.


import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class SingleCookieTest {

    @Test
    public void testSingleCookie() {
        RestAssured.baseURI = "https://jsonplaceholder.typicode.com";

        given()
            .cookie("sessionId", "abc123")
            .when()
                .get("/posts")
            .then()
                .statusCode(200);
    }
}

Explanation:

  • cookie("sessionId", "abc123"): Adds a cookie named sessionId with the value abc123.
  • Note: jsonplaceholder.typicode.com doesn’t require cookies, so this is a illustrative example. Use a cookie-based API for real-world testing.

Option 2: Adding Multiple Cookies

Use the cookies() method to add multiple cookies.


import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class MultipleCookiesTest {

    @Test
    public void testMultipleCookies() {
        RestAssured.baseURI = "https://jsonplaceholder.typicode.com";

        given()
            .cookies(
                "sessionId", "abc123",
                "userToken", "xyz789"
            )
            .when()
                .get("/posts")
            .then()
                .statusCode(200);
    }
}

Explanation:

  • cookies(): Adds multiple cookies in a single call, sent in the Cookie header.
  • This is useful for APIs requiring multiple session or authentication cookies.

Using Request Specification for Headers and Cookies

To reuse headers and cookies across tests, include them in a Request Specification.


import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class HeadersCookiesSpecTest {

    private static RequestSpecification requestSpec;

    @BeforeAll
    public static void setup() {
        requestSpec = new RequestSpecBuilder()
            .setBaseUri("https://jsonplaceholder.typicode.com")
            .addHeader("Content-Type", "application/json")
            .addHeader("Accept", "application/json")
            .addCookie("sessionId", "abc123")
            .build();
    }

    @Test
    public void testWithSpec() {
        given()
            .spec(requestSpec)
            .when()
                .get("/posts")
            .then()
                .statusCode(200)
                .body("[0].id", notNullValue());
    }

    @Test
    public void testWithAdditionalHeader() {
        given()
            .spec(requestSpec)
            .header("Custom-Header", "ExtraValue")
            .when()
                .get("/users")
            .then()
                .statusCode(200)
                .body("[0].id", notNullValue());
    }
}

Explanation:

  • addHeader() and addCookie(): Add headers and cookies to the Request Specification.
  • spec(requestSpec): Applies the specification to each test.
  • The second test adds an additional header, showing how to combine specifications with test-specific settings.
Pro Tip: Use Request Specifications for common headers and cookies to reduce repetition and ensure consistency across tests.

Verify Setup with pom.xml

Ensure your pom.xml includes the necessary dependencies for REST Assured and JUnit:



    
        io.rest-assured
        rest-assured
        5.4.0
        test
    
    
        org.junit.jupiter
        junit-jupiter
        5.10.2
        test
    
    
        org.hamcrest
        hamcrest
        2.2
        test
    

Run the tests using mvn test or your IDE’s test runner to confirm the setup.

Tips for Beginners

  • Check API Documentation: Verify required headers and cookies in the API’s documentation.
  • Use Standard Headers: Common headers like Content-Type and Authorization are often mandatory.
  • Test with Real APIs: For cookie-based testing, use APIs requiring session cookies instead of jsonplaceholder.typicode.com.
  • Enable Logging: Use RestAssured.enableLoggingOfRequestAndResponseIfValidationFails() to debug header or cookie issues.
Troubleshooting Tip: If the API returns a 401 Unauthorized or 400 Bad Request error, check for missing or incorrect headers/cookies. Ensure they match the API’s requirements.

What’s Next?

In the next post, we’ll cover GET Requests, exploring how to perform and validate GET requests in REST Assured for retrieving data from APIs. Stay tuned for more hands-on examples!