Skip to main content

Day 10: Working with Response Headers

Day 10: Working with Response Headers

In Rest Assured, response headers play a crucial role in API testing as they provide valuable information about the response received from an API endpoint. These headers contain metadata about the response, such as content type, cache control, authentication details, and more. Understanding and working with response headers is essential for validating the response and ensuring the API's proper functioning.

To work with response headers in Rest Assured, we can use various methods and techniques. Let's dive into more detail about working with response headers and how to use methods like Header and Headers to validate them.

  1. Retrieving a Specific Header:
  2. We can retrieve a specific header from the response using the getHeader() method. This method takes the header name as an argument and returns the corresponding Header object. For example:

    
          Response response = RestAssured.get("https://api.example.com/users");
    Header contentTypeHeader = response.getHeader("Content-Type");
      
    

    In the above code, we send a GET request to an API endpoint and store the response in the response variable. We then retrieve the "Content-Type" header using the getHeader() method and assign it to the contentTypeHeader variable.

  3. Accessing Header Values:
  4. Once we have obtained a specific header, we can access its value using the getValue() method. This method returns the value of the header as a string. For example:

    
           
           String contentType = contentTypeHeader.getValue();
      
    

    Here, we retrieve the value of the "Content-Type" header and assign it to the contentType variable.

  5. Validating Header Values:
  6. We can validate the value of a header by comparing it against an expected value. This is useful to ensure that the API is returning the expected headers. For example:

    
           String expectedContentType = "application/json; charset=utf-8";
    assert contentType.equals(expectedContentType) : "Unexpected Content-Type header value";
      
    

    In the above code, we compare the value of the "Content-Type" header (contentType) with an expected value (expectedContentType). If the validation fails, an assertion error is thrown with the specified message.

  7. Retrieving All Headers:
  8. To retrieve all headers from the response, we can use the getHeaders() method. This method returns a Headers object containing all the headers. We can then iterate over the headers and access their names and values. For example:

    
           Headers allHeaders = response.getHeaders();
    for (Header header : allHeaders) {
        String headerName = header.getName();
        String headerValue = header.getValue();
        // Perform necessary operations with the header information
    }
             
    

    In the above code, we retrieve all the headers from the response and iterate over them using a for-each loop. Within the loop, we can access the name and value of each header using the getName() and getValue() methods, respectively.

    By working with response headers in Rest Assured, you can validate important information such as content type, caching, and authentication details. This helps in verifying the behavior and adherence to standards of the API under test. Additionally, handling and validating response headers contribute to building robust and reliable API test suites.

Sample Code :
       
       import io.restassured.RestAssured;
import io.restassured.http.Header;
import io.restassured.response.Response;

public class ResponseHeadersExample {
    public static void main(String[] args) {
        // Send a GET request to an API endpoint
        Response response = RestAssured.get("https://api.example.com/users");

        // Get a specific header from the response
        Header contentTypeHeader = response.getHeader("Content-Type");
        System.out.println("Content-Type header: " + contentTypeHeader.getValue());

        // Validate a specific header value
        String expectedContentType = "application/json; charset=utf-8";
        assert contentTypeHeader.getValue().equals(expectedContentType) : "Unexpected Content-Type header value";

        // Get all headers from the response
        Headers allHeaders = response.getHeaders();
        for (Header header : allHeaders) {
            System.out.println(header.getName() + ": " + header.getValue());
        }
    }
}
         

Comments

Popular posts from this blog

How to integrate Autoit with selenium

For handling Dialog boxes which are not web based, Then Autoit is the best Tool to handle this These are the following code should written in Selenium Selenium Code: try { String[] commands = new String[] {}; commands = new String[] { "Path" }; // location of Autoit EXE file Runtime.getRuntime().exec(commands); } catch (IOException e) { } Autoit code: if WinWaitActive("File Upload") Then ;MsgBox(2,"window found","Found the window") WinActivate("File upload") Send("!n") Sleep(5000) Send("File path") SEND("{ENTER}") ;location of the file you want to a to the form and submit ;Send("!O") Else MsgBox(1,"TimeOut","Timed out") EndIf Here we need to create a Exe file for the Autoit script and that path should be mentioned in selenium code.

Reflection API

The Reflection API allows Java code to examine classes and objects at run time.The new reflection classes allow you to call another class's methods dynamically at run time. With the reflection classes, you can also examine an instance's fields and change the fields' contents. The Reflection API consists of the java.lang.Class class and the java.lang.reflect classes: Field, Method, Constructor, Array, and Modifier. Example program: import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; // calling method whose name we store in a variable public class ReflectionAPI { public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { String x="sampleTest"; //String meth=read name from xls file Method method= ReflectionAPI.class.getMethod(x, String.class); method.invoke(method, "welcome"); System.out.

Collection API

CollectionAPI: The Java Collections API's provide Java developers with a set of classes and interfaces that makes it easier to handle collections of objects. In a sense Collection's works a bit like arrays, except their size can change dynamically, and they have more advanced behaviour than arrays. Example program: import java.util.ArrayList; import java.util.Hashtable; public class CollectionAPI { /** * @param args */ public static void main(String[] args) { int names[] = new int[5]; ArrayList list = new ArrayList (); list.add("Ramu");//0 list.add("Venu");//1 list.add("Raju");//2 System.out.println(list.size()); for(int i =0; i<=list.size(); i++) { System.out.println(list.get(i)); } // key - value // key - unique Hashtable table = new Hashtable (); table.put("name", "Hyderabad"); table.put("place", "Mumbai"); table.put("na