Understanding Request Chaining - Notes By ShariqSP

Understanding Request Chaining

Request chaining is a process where the response from one API request is used as input for another API request. It is particularly useful in scenarios where multiple dependent API calls need to be executed in sequence. For example, creating a user and then immediately deleting the same user involves chaining the requests because the id from the registration response is required to delete the user.

Example: Register User and Delete User

Let's consider an example where we first register a user using a POST API and then delete the same user using a DELETE API. Below are the details:

Base URL

http://apitesting.shariqsp.com:8080

1. Register User

The registration endpoint is used to create a new user.

  • HTTP Method: POST
  • Endpoint: /api/users/register
  • Payload:
            {
                "id": 123,
                "username": "shariq",
                "email": "me@shariq.com",
                "mobile": "987654321",
                "password": "password123"
            }
                

Sample Request:

POST http://apitesting.shariqsp.com:8080/api/users/register

Expected Response:

            {
                "success": true,
                "message": "User registered successfully",
                "data": {
                    "id": 123,
                    "username": "shariq"
                }
            }
                

2. Delete User

Once the user is registered, we use the id from the registration response to delete the user.

  • HTTP Method: DELETE
  • Endpoint: /api/users/delete/{id}
  • Payload: None

Sample Request:

DELETE http://apitesting.shariqsp.com:8080/api/users/delete/123

Expected Response:

            {
                "success": true,
                "message": "User deleted successfully"
            }
                

How Request Chaining Works

The following steps demonstrate how request chaining works in this example:

  1. Step 1: Send a POST request to the /api/users/register endpoint with the registration JSON payload. The response contains the id of the created user.
  2. Step 2: Extract the id from the response using tools like Postman, or through code in your automation framework.
  3. Step 3: Use the extracted id to construct the DELETE request to the /api/users/delete/{id} endpoint and execute it.

Request Chaining in Postman

Postman is a popular tool for testing APIs and supports request chaining using variables. Here's how to implement request chaining in Postman:

  1. Step 1: In the registration request, save the id from the response using a Postman script in the "Tests" tab:
                pm.environment.set("userId", pm.response.json().data.id);
                            
  2. Step 2: Use the saved variable in the delete request URL:
                DELETE http://apitesting.shariqsp.com:8080/api/users/delete/{{userId}}
                            
  3. Step 3: Run the requests sequentially in a collection to chain them.

Advantages of Request Chaining

  • Simplifies testing of workflows with multiple dependent API calls.
  • Ensures dynamic data usage across requests.
  • Automates complex scenarios in API testing frameworks like Postman or REST-assured.

Implementing Request Chaining with REST-Assured

REST-Assured allows you to dynamically capture data from an API response and use it in subsequent requests. This is essential for request chaining, where one request's output serves as the input for another. Here, we demonstrate registering a user and then deleting that user using REST-Assured, with data captured dynamically from the first response.

Prerequisites

  • Java Development Kit (JDK) installed on your system.
  • Maven dependency for REST-Assured:
                <dependency>
                    <groupId>io.rest-assured</groupId>
                    <artifactId>rest-assured</artifactId>
                    <version>5.3.0</version>
                </dependency>
                            

Code Implementation

The following code demonstrates how to capture the id from the registration response and use it dynamically in the delete request:

            import io.restassured.RestAssured;
            import io.restassured.response.Response;
            import static io.restassured.RestAssured.*;
            import static org.hamcrest.Matchers.*;
            
            public class DynamicRequestChaining {
            
                public static void main(String[] args) {
                    // Base URI for the API
                    RestAssured.baseURI = "http://apitesting.shariqsp.com:8080";
            
                    // Step 1: Register a user and capture the ID from the response
                    String registerPayload = """
                    {
                        "username": "shariq",
                        "email": "me@shariq.com",
                        "mobile": "987654321",
                        "password": "password123"
                    }
                    """;
            
                    Response registerResponse = given()
                        .header("Content-Type", "application/json")
                        .body(registerPayload)
                    .when()
                        .post("/api/users/register")
                    .then()
                        .statusCode(200) // Ensure the request was successful
                        .body("success", equalTo(true)) // Validate success flag
                        .extract()
                        .response();
            
                    // Extract the user ID dynamically from the response
                    int userId = registerResponse.jsonPath().getInt("data.id");
                    System.out.println("Registered User ID: " + userId);
            
                    // Step 2: Delete the user using the captured ID
                    given()
                        .pathParam("id", userId) // Use the captured ID dynamically
                    .when()
                        .delete("/api/users/delete/{id}")
                    .then()
                        .statusCode(200) // Ensure the deletion was successful
                        .body("success", equalTo(true)) // Validate success flag
                        .body("message", equalTo("User deleted successfully"));
            
                    System.out.println("User with ID " + userId + " deleted successfully.");
                }
            }
                

Explanation of the Code

  • Register Request:
    • A POST request is sent to the /api/users/register endpoint with the user registration JSON payload.
    • The response is validated for success and the id is dynamically extracted using jsonPath().getInt("data.id").
  • Delete Request:
    • The captured id is used as a path parameter in the DELETE request to /api/users/delete/{id}.
    • The response is validated to ensure that the user was deleted successfully.

Advantages of Dynamic Request Chaining

  • Eliminates hardcoding, making tests more robust and reusable.
  • Ensures that requests are executed with real-time data from API responses.
  • Enables seamless automation of complex workflows in API testing.

Best Practices

  • Always validate API responses before extracting data to ensure integrity.
  • Use descriptive variable names for captured data to maintain readability.
  • Encapsulate request chaining logic into reusable methods or classes for better maintainability.