Read HTTP Header with REST Assured

In this tutorial, you will learn how to retrieve the HTTP header value from an HTTP response while testing your RESTful API using REST Assured.

What are HTTP Headers?

HTTP headers are a fundamental part of the HTTP protocol, which is the protocol used to transfer data over the web. An HTTP header is a piece of information that is sent from the client (usually a web browser) to the server, or from the server to the client. HTTP headers provide additional information about the request or response, such as the type of content being transferred, the encoding of the content, or the authentication credentials of the user.

HTTP headers are made up of a header name and a header value, separated by a colon. For example, the Content-Type header might have a value of application/json. HTTP headers are often represented in key-value pairs, with the header name acting as the key and the header value acting as the value.

HTTP headers can be divided into several categories, including:

  • General headers: These headers apply to both requests and responses and provide general information about the message, such as the date and time it was sent.
  • Request headers: These headers are sent by the client as part of a request and provide additional information about the request, such as the method being used (e.g., GET or POST) and the URL of the requested resource.
  • Response headers: These headers are sent by the server as part of a response and provide additional information about the response, such as the status code (e.g., 200 OK or 404 Not Found) and the encoding of the content.
  • Entity headers: These headers provide information about the content being transferred, such as the length of the content or the encoding used.

HTTP headers are a powerful tool for transmitting information over the web and are used extensively in RESTful APIs. Understanding HTTP headers is essential for developers who want to build robust and efficient web applications.

Types of HTTP Headers

HTTP headers can be classified into several types based on their purpose and usage. Understanding the different types of headers is essential when reading HTTP headers in REST Assured. Here are the most common types of HTTP headers:

Request Headers

Request headers are included in an HTTP request and provide additional information about the request being made. They are sent from the client to the server and can be used to specify the type of content being sent, the language of the content, or the authentication credentials required to access the resource.

Some examples of request headers include:

  • Accept: specifies the MIME types that the client can handle in the response
  • Content-Type: specifies the MIME type of the data being sent in the request
  • Authorization: contains authentication credentials required to access a resource

Response Headers

Response headers are included in an HTTP response and provide additional information about the response being sent. They are sent from the server to the client and can be used to provide information about the server, the type of content being sent, or the caching options for the resource.

Some examples of response headers include:

  • Content-Type: specifies the MIME type of the data being sent in the response
  • Cache-Control: specifies caching options for the resource
  • Server: specifies the server software being used to serve the response

Entity Headers

Entity headers are included in both requests and responses and provide information about the data being sent in the message body. They can be used to specify the encoding of the data, the language of the data, or the length of the data.

Some examples of entity headers include:

  • Content-Encoding: specifies the encoding of the data in the message body
  • Content-Language: specifies the language of the data in the message body
  • Content-Length: specifies the length of the data in the message body

Understanding the different types of HTTP headers and their purpose is essential when reading HTTP headers in REST Assured. It can help you identify the headers you need to read and extract the information you need from them.

Importance of Reading HTTP Headers

HTTP headers play an important role in communication between a client and a server. They contain metadata that provide additional information about the message being sent, such as the type of content being sent, the encoding used, and any authentication information.

When testing APIs using REST Assured, it is important to read the HTTP headers returned by the server to ensure that the API is functioning as expected. Here are some reasons why reading HTTP headers is important:

1. Ensure Compatibility

HTTP headers are used to indicate the format of the response, including the type of content being returned and the character encoding used. By reading the headers, you can ensure that your application is compatible with the API being tested.

2. Debugging and Troubleshooting

HTTP headers can also be used to provide additional information about the response, such as the status of the request and any errors that may have occurred. By reading the headers, you can quickly identify any issues and troubleshoot them.

3. Security and Authorization

HTTP headers can be used for authentication and authorization purposes, such as sending access tokens or cookies. By reading the headers, you can ensure that the API is properly secured and that only authorized users are able to access it.

4. Performance and Optimization

HTTP headers can also be used to optimize performance, such as by specifying caching options or compressing responses. By reading the headers, you can identify any areas where performance can be improved.

In summary, reading HTTP headers is an essential part of API testing using REST Assured. It can help ensure compatibility, simplify debugging and troubleshooting, ensure proper security and authorization, and optimize performance.

API Endpoint to Test

Assuming that we have configured Spring Security in our RESTful Web Services application, we can define a Web Service Endpoint that serves as a user authentication endpoint. This endpoint accepts a username and password and upon successful authentication, responds with an authorization header and a userId included in the HTTP headers of the response:

http://localhost:8080/login

This web service endpoint accepts an HTTP POST request with the following JSON payload:

{
    "email": "test9@test.com",
    "password": "123"
}

Reading HTTP Header

Here is an example of a REST Assured test method that sends an HTTP POST request to the web service endpoint mentioned above and reads the HTTP response headers, including:

  • Authorization header.
  • Custom UserId header value.

Below is a short code snippet to read the value of the 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 example that demonstrates how to read 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", "test9@test.com");
        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);
    }
}

Conclusion

In this tutorial, we have learned how to use REST Assured to read HTTP headers in a response from a RESTful web service. We saw how to extract specific header values using REST Assured methods, and we provided a complete code example for reading all headers in a response.

We also discussed the importance of reading HTTP headers in API testing, highlighting their role in ensuring compatibility, debugging and troubleshooting, security and authorization, and performance optimization.

Ready to tackle the complexities of testing RESTful web services? Visit the Testing Java Code page to access our comprehensive tutorial on using REST Assured. Discover expert techniques to validate API responses, handle authentication, and perform thorough testing of your web services.

Frequently asked questions

  • What is the role of HTTP headers in caching and content negotiation?
    HTTP headers play a crucial role in caching and content negotiation in API interactions. The headers provide information to the client and server about caching strategies, content types, and encoding preferences, among other things. For example, the “Cache-Control” header can be used to control caching behaviour, while the “Accept” header can be used to indicate the preferred content type for a request. By using these headers effectively, developers can optimize the performance and efficiency of their APIs.
  • Can I customize HTTP headers for specific test scenarios in REST Assured?
    Yes, REST Assured provides several methods that enable customization of HTTP headers for specific test scenarios. For instance, you can use the “given()” method to set specific headers for a request, or the “header()” method to add or replace headers in a request or response.
  • Can I use REST Assured to test APIs that use cookies for authentication?
    Yes, you can use REST Assured to test APIs that use cookies for authentication. You can add cookies to a REST Assured request using the cookies() method, and extract cookies from a response using the detailedCookies() method.


Leave a Reply

Your email address will not be published. Required fields are marked *