REST Assured 48 - How To Pass Headers In Rest Assured Requests

Keywords: API testing

REST Assured series summary 48 - how to pass headers in rest assured requests

prerequisite

Add rest assured dependency package

 <!-- REST Assured -->
 <dependency>
   <groupId>io.rest-assured</groupId>
   <artifactId>rest-assured</artifactId>
   <version>4.4.0</version>
</dependency>

What is a Header?

Header is the metadata of request and response of an API. For example, the payload we send to the request needs to be in a certain format, JSON or XML or other types. Similarly, the response may be in some format. We can use the headers of request and response to help the server and client better understand request and response.

We can also send Authorization authentication information through headers. When we initiate an API, many default headers will be added to the request and response to establish a safer and faster connection. Some commonly used headers are "content type", "Accept", "Authorization", "ETag", etc

Headers may be a key value pair, or a key may have multiple values. Next, let's see how rest assured passes headers.

How to add headers to Rest Assured request?

There are many overloaded methods "headers()" and "header()" in the RequestSpecification and ResponseSpecification interfaces. Use the headers() or header() methods of RequestSpecification to send a request with headers, and the headers() or header() methods of ResponseSpecification to assert the headers of the received response. There are some subtle differences between the two. Don't think we can add headers to a response through the headers () or header () method of ResponseSpecification.

Overloaded headers() and header() methods

1. RequestSpecification headers(String firstHeaderName, Object firstHeaderValue, Object... headerNameValuePairs);
2. RequestSpecification headers(Map<String, ?> headers);
3. RequestSpecification headers(Headers headers);
4. RequestSpecification header(String headerName, Object headerValue, Object... additionalHeaderValues);
5. RequestSpecification header(Header header);

Add a header in several ways
Suppose a header is named "someHeader" and its value is "somevalue", we can pass the header in the request in the following ways.

// Add a header as key value
RestAssured.given().header("someHeader","somevalue");
RestAssured.given().headers("someHeader","somevalue");
		
// Add header as a Map
Map<String,String> requestHeaders = new HashMap<>();
requestHeaders.put("someHeader","somevalue");
RestAssured.given().headers(requestHeaders);
		
// Add header using Header class
Header requestHeader1 = new Header("someHeader","somevalue");
RestAssured.given().header(requestHeader1);
		
// Add header using Header and Headers class
Header requestHeader2 = new Header("someHeader","somevalue");
Headers requestHeaders3 = new Headers(requestHeader2);
RestAssured.given().headers(requestHeaders3);

Observe the overloaded headers() and header() methods above. They can receive different forms of parameters. header() is used to add a single header, while headers() is used to add multiple headers.
Header is a class that represents a header. The Headers class code is a collection of multiple Headers. You need to instantiate Headers or Headers to create header information.

Add duplicate header

Duplicate headers can be passed, and their values will not be overwritten. For example, if you pass two values value1 and value 2 to a header1, they will be passed in the form of header1=value1 and header1=value2. This is the default behavior. Even if the header values are duplicate, they will be sent in this way.

You can call the same method or mixed method multiple times. All headers will be added to the request, whether unique or duplicate. If a header has multiple values, you can add it with a special method, as follows:

RequestSpecification header(String headerName, Object headerValue, Object... additionalHeaderValues);

For example:

RestAssured.given().header("someHeader","someFirstvalue", "someSecondvalue");

Note that a Map cannot have duplicate key s, so if you need to pass a header with multiple values, you can't use a Map.

How do I change the default header merge behavior?
If you add different values of the same header multiple times, the value of the default header will not be overwritten (except "content type" and "Accept"). However, you can override this behavior with the HeaderConfig class.

// Define headers that should be be merged instead of overwritten 
mergeHeadersWithName(headerName, additionalHeaderNames)
// Define headers that should be overwritten instead of merged
overwriteHeadersWithName(headerName, additionalHeaderNames)

For example:

RestAssuredConfig.config().headerConfig(HeaderConfig.headerConfig().overwriteHeadersWithName("header1"));

If the two values value1 and value2 of header1 are passed, they will not be merged and only the last value will be taken. For example, header1 has only one value and is passed with header1 = value2.

RestAssuredConfig.config().headerConfig(HeaderConfig.headerConfig().mergeHeadersWithName("header1"));

If you want to pass a header1 with two values value1 and value2, it will be combined into header1=value1 and header1=value2, which is the default behavior.

code:

import java.util.HashMap;
import java.util.Map;


import io.restassured.RestAssured;
import io.restassured.config.HeaderConfig;
import io.restassured.config.RestAssuredConfig;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import org.junit.Test;

public class AddingHeaders {

    @Test
    public void addKeyvaluePairHeaders() {

        // Add a header as key value
        System.out.println("Add a header as key value");
        RestAssured.given()
                .header("someHeader","somevalue")
                .headers("someHeader","somevalue")
                .log().headers()
                .get("https://restful-booker.herokuapp.com/booking/10");

        // Add header as a Map
        System.out.println("Add header as a Map");
        Map<String,String> requestHeaders = new HashMap();
        requestHeaders.put("someHeader","somevalue");
        RestAssured.given()
                .headers(requestHeaders)
                .log().headers()
                .get("https://restful-booker.herokuapp.com/booking/10");


        // Add header using Header class
        System.out.println("Add header using Header class");
        Header requestHeader1 = new Header("someHeader","somevalue");
        RestAssured.given()
                .header(requestHeader1)
                .log().headers()
                .get("https://restful-booker.herokuapp.com/booking/10");

        // Add header using Header and Headers class
        System.out.println("Add header using Header and Headers class");
        Header requestHeader2 = new Header("someHeader","somevalue");
        Headers requestHeaders3 = new Headers(requestHeader2);
        RestAssured.given()
                .headers(requestHeaders3)
                .log().headers()
                .get("https://restful-booker.herokuapp.com/booking/10");

        // Add header with multiple values
        System.out.println("Add header with multiple values");
        RestAssured.given()
                .header("someHeader","someFirstvalue", "someSecondvalue")
                .log().headers()
                .get("https://restful-booker.herokuapp.com/booking/10");

        // Changing default behavior of merging
        System.out.println("Changing default behavior of merging");
        RestAssured.given()
                .config(RestAssuredConfig.config().headerConfig(HeaderConfig.headerConfig().mergeHeadersWithName("header1")))
                .header("header1","someFirstvalue")
                .header("header1","someSecondvalue")
                .log().headers()
                .get("https://restful-booker.herokuapp.com/booking/10");

        // Change overwrite behavior if not
        System.out.println("Change overwrite behavior if not");
        RestAssured.given()
                .config(RestAssuredConfig.config().headerConfig(HeaderConfig.headerConfig().overwriteHeadersWithName("header1")))
                .header("header1","someFirstvalue")
                .header("header1","someSecondvalue")
                .log().headers()
                .get("https://restful-booker.herokuapp.com/booking/10");

    }
}

Output:

Add a header as key value
Headers:		someHeader=somevalue
				someHeader=somevalue
				Accept=*/*
Add header as a Map
Headers:		someHeader=somevalue
				Accept=*/*
Add header using Header class
Headers:		someHeader=somevalue
				Accept=*/*
Add header using Header and Headers class
Headers:		someHeader=somevalue
				Accept=*/*
Add header with multiple values
Headers:		someHeader=someFirstvalue
				someHeader=someSecondvalue
				Accept=*/*
Changing default behavior of merging
Headers:		header1=someFirstvalue
				header1=someSecondvalue
				Accept=*/*
Change overwrite behavior if not
Headers:		header1=someSecondvalue
				Accept=*/*

Posted by leoden on Tue, 21 Sep 2021 04:56:18 -0700