Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are Headers?
3.
How to Pass Headers in Rest Assured Requests?   
3.1.
Passing Them in a Key-Value Format Using The Header Method.
3.2.
Passing Them as a Map Using The Headers Method.
3.3.
Passing Them as a List Using The Headers Method.
4.
How to Retrieve Headers In Rest Assured Requests?   
5.
Frequently Asked Questions
5.1.
What are headers?
5.2.
How to change the default merging behavior of headers?
5.3.
Can we pass duplicate headers?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

How To Pass or retrieve Headers In Rest Assured Requests

Author Tisha
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

In this article, we will learn about how to pass or retrieve headers in rest assured requests. We will see what the headers are and different methods with which we can pass or retrieve headers in rest assured requests.

Introduction

What are Headers?

Headers are the data about data of request and the response of an API. It is like as We pass the request payload in a format. It can be XML, JSON or any other type. The response can be in any format. We can use the headers with requests and responses that will help the client and the server to understand responses and requests well.

The headers can also be used to pass the authorization information. When the API is hit, many headers are added with responses and requests to make a better and secure connection. Some encountered headers are “ETag”, “Content-Type”, “Authorization”, “Accept” etc.

Headers can have key with multi-value or key-value pair. Below we will learn how to pass headers in rest assured requests.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

How to Pass Headers in Rest Assured Requests?   

There are more than one way with which we can pass headers in Rest Assured Requests. Below are the ways:

Passing Them in a Key-Value Format Using The Header Method.

We can pass headers in rest assured requests is by passing them in a key value format using the header method. Below is the example of this.

Example:

Response r = given()
.baseUri("https://www.codingninjas.com/")
.header("header1", "value1")
.header("header2", "value2")
.get("/about/our-team.htm");

Passing Them as a Map Using The Headers Method.

We can also pass headers in rest assured requests is by passing them as a map using the headers method. Below is the example of this.

Example:

Map<String,Object> m = new HashMap<String,Object>();
m.put("header1", "value1");
m.put("header2, "value2");
Response r = given()
.baseUri("https://www.codingninjas.com/")
.headers(m)
.get("/about/our-team.htm");

Passing Them as a List Using The Headers Method.

The third method with which we can pass headers in rest assured requests is by passing them as a List using the headers method. Below is the example of this.

Example:

List<Header> h = new ArrayList<Header>();
h.add(new Header("header1", "value1"));
h.add(new Header("header2", "value2"));
Response r = given()
.baseUri("https://www.codingninjas.com/")
.headers(h)
.get("/about/our-team.htm");

How to Retrieve Headers In Rest Assured Requests?   

Retrieve headers

When we make the API request we need to extract the response as Response. Here Response is an interface that shows the response of the request generated by the REST Assured. An example can be seen below:-


Response response= RestAssured
    .given()
    .get("https://www.codingninjas.com/");

 

OR

Response response= RestAssured
    .given()
    .get("https://www.codingninjas.com/")
    .then()
    .extract()
    .response();


The response interface gives four methods to retrieve the header.

getHeader(String headername) or header(String headerName) or  – it provides a single header value that is associated with the given name


headers() or getHeaders() – Get all the response headers

REST Assured contains the methods that are only there for syntactic sugar. The above two methods are examples of that. getHeader() sounds much better than header(). We know that a header is a key-multi value pairs or key-value. If we want to retrieve a header by its name then we use getHeader(String headerName) or header(String headerName) that returns a String which is the value of that header. If we want to retrieve all headers of response then we use headers() or getHeaders() that returns Headers object.

package javaPackageName;
​
import java.util.Map;
import java.util.HashMap;
​
import io.restassured.http.Header;
import io.restassured.RestAssured;
import io.restassured.http.Headers;
import org.testng.annotations.Test;
import io.restassured.response.Response;
​
public class RestAssuredHeader {

@Test
public void xHeaderxValues() {

/*Adding Header as Key Value*/
Response objRes1 = RestAssured
.given()
.header("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9")
.get("http://localhost:8080/tisha");

System.out.println("Method 1 -> ");
System.out.println("Content-Type: "+objRes1.contentType());
System.out.println("Status Code: "+objRes1.statusCode());

/*Adding Header as Map*/
Map<String, String> map = new HashMap<String, String>();
map.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");

Response objRes2 = RestAssured
.given()
.headers(map)
.get("https://rest-assured.io/tisha");

System.out.println("Method 2 -> ");
System.out.println("Status Code: "+objRes2.getStatusCode());

Headers objHeaders1 = objRes2.getHeaders();
System.out.print(objHeaders1.get("content-encoding"));
System.out.print("\n");

/*Adding Header using Header Class*/
Header objHeader1 = new Header("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
Response objRes3 = RestAssured
.given()
.header(objHeader1)
.get("https://rest-assured.io/tisha");

System.out.println("Method 3 -> ");
System.out.println("Status Code: "+objRes3.getStatusCode());

/*Retrieve Headers*/
Headers objHeaders2 = objRes3.getHeaders();
System.out.print(objHeaders2.get("Connection"));
System.out.print("\n");

/*Adding Header using Header and Header Class*/
Header objHeader2 = new Header("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
Headers objHeader3 = new Headers(objHeader2);

Response objRes4 = RestAssured
.given()
.headers(objHeader3)
.get("https://rest-assured.io/tisha");

System.out.println("Method 4 -> ");
System.out.println("Status Code: "+objRes4.getStatusCode());

/*Adding header with multiple values*/
Response objRes5 = RestAssured
.given()
.header("Accept","NextOneWillBeHeader", "TishaHeader")
.log()
.headers()
.get("https://rest-assured.io/tisha");

System.out.println("Method 5 -> ");
System.out.println("Status Code: "+objRes5.getStatusCode());

/*Retrieve Header*/
String objHeaders3 = objRes5.getHeader("Content-Type");
System.out.print(objHeaders3);
System.out.print("\n");
}
}

Output:

Output2

Frequently Asked Questions

What are headers?

Headers are the data about data of request and the response of an API. It is like as We pass the request payload in a format. It can be XML, JSON, or any other type.

How to change the default merging behavior of headers?

By default, the header value can not be overwritten if it is used multiple times. They are merged by default except “Accept” and “Content-Type”. But It can be override for the individual headers by using HeaderConfig class.

Can we pass duplicate headers?

Yes, we can pass duplicate headers and there will not be any overwritten values. For example, If you pass two values of header1 as v1 and v2 then it will be merged and passed as header1=v1 and header1=v2.

Conclusion

In this article, we have learned about headers and how to Pass or retrieve Headers In Rest Assured Requests.

Recommended read: 

You can learn the basics of Java and data structures and algorithms in Java on Coding Ninjas. Refer to our guided path on code studio to learn more about DSA Competitive Programming, Javascript System Design, etc. Enroll in our courses and refer to the mock test and problems available. Also, look at the interview experiences for placement preparations.

Happy Learning Ninjas.

Previous article
Fetching Values From JSON Objects In REST Assured
Next article
How to Set, Retrieve and Assert Content-Type for Request in Rest Assured
Live masterclass