REST Assured GET HTTP Header Value

In this tutorial, you are going to learn how to get HTTP Header value from HTTP Response when testing your RESTful API with REST Assured.

Let’s assume that we have configured Spring Security in our RESTful Web Services application and now we have the following Web Service Endpoint which acts as a user Authentication endpoint. This web service endpoint accepts username and password and if user authentication is successful, returns an authorization header and a userId as Response HTTP Headers.

Web service endpoint

http://localhost:8080/login

this Web Service endpoint accepts HTTP Post request with the below JSON Payload:

{
    "email": "[email protected]",
    "password": "123"
}

Get HTTP Header Value in REST Assured Test Method

Below is an example of REST Assured Test method which sends HTTP Post Request to the above-mentioned web service endpoint and reads HTTP Response Headers:

  • Authorization Header, and
  • Custom UserId Header value.

Below is a complete example of my Test class but here is short code snipped to read the value of Authorization header from the Response object:

Response response = httpRequest.post("/login");
String authorizationHeader = response.getHeader("Authorization");

Reading HTTP Headers Complete Code Example

Here is a complete code examlpe that demonstrates how to read two HTTP Headers set to a Response object.

package com.appsdeveloperblog.app.ws.mobileappws;

import com.google.gson.JsonObject;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.Assert;
import org.junit.Test;

/**
 *
 * @author skargopolov
 */
public class APITest {

    @Test
    public void validate_response_headers_test() {
        RestAssured.baseURI = "http://localhost:8888";
        RequestSpecification httpRequest = RestAssured.given();
        httpRequest.header("Content-Type", "application/json");

        // Create new JSON Object
        JsonObject loginCredentials = new JsonObject();
        loginCredentials.addProperty("email", "[email protected]");
        loginCredentials.addProperty("password", "123");

        httpRequest.body(loginCredentials.toString());

        Response response = httpRequest.post("/login");
        String authorizationHeader = response.getHeader("Authorization");
        String userIdHeader = response.getHeader("UserId");

        Assert.assertNotNull(authorizationHeader);
        Assert.assertNotNull(userIdHeader);
    }
}

I hope this short tutorial on REST Assured was of some value to you. Have a look at the below list of video courses that teach how to use REST Assured to test RESTful Web Services and hopefully you will find one of them useful.