Answer
API Chaining in Rest Assured
API chaining is a technique to make multiple API requests in a sequence, where each request''s response becomes the basis for the next request. This is often used to test scenarios that involve multiple API endpoints or dependent operations.
Example Scenario
Let''s chain these operations:
- ✓Create a user (POST)
- ✓Retrieve the created user''s details (GET)
- ✓Update the user''s information (PUT)
- ✓Verify the updated details (GET)
Java
import io.restassured.RestAssured;
import io.restassured.response.Response;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class ApiChainingExample {
private static String baseURL = "https://reqres.in/api";
@Test
public void testApiChaining() {
// Step 1: Create a user — extract the response JSON to get the user ID
String createUserResponse = given()
.contentType(ContentType.JSON)
.body("{ \"name\": \"John\", \"email\": \"john@example.com\" }")
.when()
.post(baseURL + "/users")
.then()
.statusCode(201)
.extract()
.response()
.asString();
System.out.println("Create Response: " + createUserResponse);
// Step 2: Extract the user ID from the creation response
String userId = RestAssured
.given()
.when()
.get(baseURL + "/users/{userId}", createUserResponse)
.then()
.statusCode(200)
.extract()
.path("id");
System.out.println("User ID: " + userId);
// Step 3: Update the user''s information using the extracted ID
RestAssured.given()
.contentType(ContentType.JSON)
.body("{ \"name\": \"Updated John\", \"email\": \"updated_john@example.com\" }")
.when()
.put(baseURL + "/users/{userId}", userId)
.then()
.statusCode(200);
// Step 4: Verify the updated user details
RestAssured.given()
.when()
.get(baseURL + "/users/{userId}", userId)
.then()
.statusCode(200)
.assertThat()
.body("name", equalTo("Updated John"))
.body("email", equalTo("updated_john@example.com"));
}
}
Key Points
- ✓Use
.extract().path("fieldName")to extract a specific value from the response - ✓Use
.extract().response().asString()to get the full response body - ✓Chain requests by passing extracted values as path parameters or body fields
- ✓Real-world examples: login → get token → use token for subsequent requests
