Answer
Automating DELETE Method in Rest Assured
The DELETE method removes a resource at the specified URI. A successful DELETE typically returns 204 No Content or 200 OK.
Basic DELETE Request
Java
@Test
public void testDeleteUser() {
int userId = 2;
Response response = given()
.header("Authorization", "Bearer " + token)
.when()
.delete("https://reqres.in/api/users/" + userId);
assertEquals(response.getStatusCode(), 204);
}
DELETE with Path Parameter
Java
@Test
public void deleteUserByPathParam() {
given()
.header("Authorization", "Bearer " + token)
.pathParam("id", 5)
.when()
.delete("/api/users/{id}")
.then()
.statusCode(204);
}
Verify Resource is Gone After DELETE
Java
@Test
public void testDeleteThenVerifyGone() {
int userId = 3;
// Step 1: Delete the user
given()
.header("Authorization", "Bearer " + token)
.when()
.delete("/api/users/" + userId)
.then()
.statusCode(204);
// Step 2: Verify user no longer exists
given()
.when()
.get("/api/users/" + userId)
.then()
.statusCode(404)
.body("message", equalTo("User not found"));
}
DELETE with Request Body (some APIs require it)
Java
@Test
public void deleteWithBody() {
String body = "{ \"reason\": \"Account closure requested by user\" }";
given()
.contentType(ContentType.JSON)
.body(body)
.header("Authorization", "Bearer " + token)
.when()
.delete("/api/users/5")
.then()
.statusCode(200)
.body("message", equalTo("User deleted successfully"));
}
Test Deleting Non-Existent Resource
Java
@Test
public void testDeleteNonExistentUser() {
given()
.when()
.delete("/api/users/999999")
.then()
.statusCode(404);
}
DELETE Response Codes
| Status | Meaning |
|---|---|
| 204 No Content | Deleted successfully, no body returned |
| 200 OK | Deleted successfully with response body |
| 404 Not Found | Resource didn't exist |
| 403 Forbidden | Not authorized to delete |
