Here are the key points on how and when to use the extract()
method in REST Assured:
Extracting the Response
The extract()
method is used to extract the response from the request. This allows you to store the response and perform further operations on it, such as assertions or extracting specific values.
To extract the response, you can chain the extract()
method after the then()
block:
Response response = given()
.when()
.get("/users")
.then()
.statusCode(200)
.extract()
.response();
This will store the entire response in the response
variable, which you can then use for further processing.
Extracting Specific Values
You can use extract()
to extract specific values from the response body. This is commonly done using JsonPath for JSON responses or XmlPath for XML responses.
For example, to extract the value of a specific JSON field:
int userId = given()
.when()
.get("/users/1")
.then()
.statusCode(200)
.extract()
.path("id");
This will extract the value of the “id” field from the JSON response and store it in the userId
variable.
Extracting the Response Body as a String
You can extract the entire response body as a String using extract().asString()
:
String responseBody = given()
.when()
.get("/users")
.then()
.statusCode(200)
.extract()
.asString();
This is useful when you want to perform custom parsing or validation on the response body.
Extracting Headers and Cookies
extract()
can also be used to extract headers and cookies from the response:
String contentType = given()
.when()
.get("/users")
.then()
.statusCode(200)
.extract()
.header("Content-Type");
This will extract the value of the “Content-Type” header from the response.
When to Use extract()
You should use extract()
whenever you need to store the response or extract specific values from it for further processing or assertions. It allows you to decouple the request from the validation, making your tests more readable and maintainable.
Some common use cases include:
- Storing the response to perform multiple assertions on it
- Extracting specific values for comparison with expected results
- Parsing the response body for custom validation logic
- Extracting headers or cookies for verification
By leveraging extract()
, you can write more robust and flexible tests with REST Assured