How to pass more than one header in a request in Rest Assured?


We can pass more than one header in a request in Rest Assured. A web service can accept headers as parameters while making a service call. The headers are represented in a key-value pair.

There is more than one way of passing multiple headers in Rest Assured −

  • Passing them in a key-value format using the header method.

Syntax

Response r = given()
.baseUri("https://www.tutorialspoint.com/")
.header("header1", "value1")
.header("header2", "value2")
.get("/about/about_careers.htm");
  • Passing them as a Map using the headers method.

Syntax

Map<String,Object> m = new HashMap<String,Object>();
m.put("header1", "value1");
m.put("header2, "value2");
Response r = given()
.baseUri("https://www.tutorialspoint.com/")
.headers(m)
.get("/about/about_careers.htm");
  • Passing them as a List using the headers method.

Syntax

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

Example

Code Implementation

import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
public class NewTest {
   @Test
   public void addMultipleHeader() {
      String baseUrl =
      "https://api.reverb.com/api/articles?page=1&per_page=24";

      //input details with multiple headers
      RequestSpecification r = RestAssured.given()
      .header("Accept", "application/hal+json")
      .header("Content-Type", "application/json")
      .header("Accept-Version", "3.0");

      //obtain get Response
      Response res = r.get(baseUrl);

      //get status code
      int c = res.getStatusCode();
      System.out.println(c);
   }
}

Output

Updated on: 19-Nov-2021

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements