Interview #68: Rest-Assured: How do you send headers and cookies with a request?

Interview #68: Rest-Assured: How do you send headers and cookies with a request?

Sending headers and cookies with a request in RestAssured is a common requirement in API testing. RestAssured is a Java library that simplifies testing RESTful APIs by providing an easy-to-use DSL for creating and verifying HTTP requests and responses.

Disclaimer: For QA-Testing Jobs/Training, WhatsApp us @ 91-9606623245

Overview:

Headers and cookies are critical in HTTP requests:

  • Headers: Provide metadata about the request, such as content type, authorization tokens, etc.
  • Cookies: Used for maintaining session state or storing information specific to the server.

In RestAssured, you can set headers and cookies for requests using methods like header(), headers(), cookie(), and cookies().


Steps to Send Headers and Cookies with RestAssured:

  1. Set Up the Environment:

  • Add RestAssured to your project by including its dependency in your pom.xml (for Maven) or build.gradle (for Gradle).

  1. Headers:

  • Use the header() method to add a single header.
  • Use the headers() method to add multiple headers at once.

  1. Cookies:

  • Use the cookie() method to add a single cookie.
  • Use the cookies() method to add multiple cookies at once.

  1. Execute the Request:

  • Choose the appropriate HTTP method (GET, POST, etc.) to send the request with the headers and cookies.


Example Code

Sending a Request with a Single Header and Single Cookie:

import io.restassured.RestAssured;

public class RestAssuredHeadersAndCookies {
    public static void main(String[] args) {
        RestAssured.baseURI = "https://api.example.com";

        RestAssured.given()
            .header("Authorization", "Bearer someAccessToken") // Add a header
            .cookie("session_id", "12345abcd")                // Add a cookie
        .when()
            .get("/endpoint")                                // Perform a GET request
        .then()
            .statusCode(200)                                 // Assert the status code
            .log().all();                                    // Log the response
    }
}        

Sending Multiple Headers and Cookies:

import io.restassured.RestAssured;
import io.restassured.http.Headers;
import io.restassured.http.Header;
import io.restassured.http.Cookies;
import io.restassured.http.Cookie;

public class RestAssuredMultipleHeadersAndCookies {
    public static void main(String[] args) {
        RestAssured.baseURI = "https://api.example.com";

        // Create multiple headers
        Headers headers = new Headers(
            new Header("Authorization", "Bearer someAccessToken"),
            new Header("Content-Type", "application/json")
        );

        // Create multiple cookies
        Cookies cookies = new Cookies(
            new Cookie.Builder("session_id", "12345abcd").build(),
            new Cookie.Builder("user_preference", "dark_mode").build()
        );

        RestAssured.given()
            .headers(headers)   // Add multiple headers
            .cookies(cookies)   // Add multiple cookies
        .when()
            .get("/endpoint")
        .then()
            .statusCode(200)
            .log().all();
    }
}        

Explanation of Key Methods:

1. Headers:

header(String name, Object value):

  • Adds a single header.
  • Example: .header("Content-Type", "application/json").

headers(Headers headers):

  • Adds multiple headers using a Headers object.
  • Example:

Headers headers = new Headers(
    new Header("Header1", "Value1"),
    new Header("Header2", "Value2")
);
.headers(headers);        

2. Cookies:

cookie(String name, Object value):

  • Adds a single cookie.
  • Example: .cookie("session_id", "12345abcd").

cookies(Cookies cookies):

  • Adds multiple cookies using a Cookies object.
  • Example:

Cookies cookies = new Cookies(
    new Cookie.Builder("cookie1", "value1").build(),
    new Cookie.Builder("cookie2", "value2").build()
);
.cookies(cookies);        

Handling Dynamic Headers and Cookies:

  • Dynamic Headers: Useful when header values change, such as for authorization tokens.

String token = getTokenFromAuthAPI();
RestAssured.given()
    .header("Authorization", "Bearer " + token)
    .when()
    .get("/secure-endpoint");        

  • Dynamic Cookies: Often retrieved after login or session creation.

String sessionId = getSessionIdFromLoginAPI();
RestAssured.given()
    .cookie("session_id", sessionId)
    .when()
    .get("/user-data");        

Logging and Debugging:

  • To log requests and responses for debugging:

RestAssured.given()
    .header("Authorization", "Bearer someAccessToken")
    .cookie("session_id", "12345abcd")
    .log().all()   // Logs the request details
.when()
    .get("/endpoint")
.then()
    .log().all();  // Logs the response details        

Advanced Use Cases:

  1. Custom Header and Cookie Interceptors: Intercept and modify requests globally for test suites.

RestAssured.filters((requestSpec, responseSpec, ctx) -> {
    requestSpec.header("Custom-Header", "CustomValue");
    return ctx.next(requestSpec, responseSpec);
});        

  1. Secure Cookie Handling: Set secure attributes for cookies.

new Cookie.Builder("name", "value")
    .setSecured(true)
    .setHttpOnly(true)
    .build();        

  1. Extracting Headers or Cookies from Responses:

Response response = RestAssured.given()
    .when()
    .get("/endpoint");

String headerValue = response.getHeader("Header-Name");
String cookieValue = response.getCookie("Cookie-Name");        

Summary:

  • Use header() and headers() to manage request headers.
  • Use cookie() and cookies() to manage request cookies.
  • Combine headers and cookies to simulate real-world scenarios such as authentication and session management.
  • Use logging and debugging to verify requests and troubleshoot issues.

RestAssured’s flexibility and simplicity make it an excellent tool for comprehensive API testing involving headers and cookies.


要查看或添加评论,请登录

Software Testing Studio | WhatsApp 91-9606623245的更多文章

社区洞察

其他会员也浏览了