Showing posts with label REST API Automation with Rest Assured. Show all posts
Showing posts with label REST API Automation with Rest Assured. Show all posts

How to Test DELETE API by Rest Assured

 



What is a DELETE API?

  • A DELETE API is an HTTP method used to remove a resource from a server.
  • It is part of the standard CRUD operations (Create, Read, Update, Delete).
  • Example scenario: If your API has a list of users, a DELETE request to /users/5 would remove the user with ID 5.

Key Points:
  • DELETE requests usually don’t return a body, but sometimes may return a confirmation message.
  • After a DELETE operation, the resource should no longer exist.
  • The server typically returns:
Status 200 (OK) if deletion is successful and a response body is returned.
Status 204 (No Content) if deletion is successful but no content is returned.
Status 404 (Not Found) if the resource does not exist.


How to Test a DELETE API in Rest Assured

Testing a DELETE API is similar to other HTTP methods:
  • Set the Base URI and Endpoint: Specify the API URL and the resource to delete.
  • Send the DELETE Request: Make a DELETE call to the resource endpoint.
  • Validate the Response:
Check the HTTP status code (200, 204, or 404 depending on the case).
Optionally, check response headers (like Content-Type).
Optionally, verify response body if the API sends a confirmation message.
  • Verify Deletion:
Perform a GET request on the same resource to ensure it is no longer available (should return 404).


To test a DELETE API using Rest Assured in Java, you follow a standard procedure:



API used for DELETE operation:

DELETE https://reqres.in/api/users/2

This would delete user with ID 2.














Steps to Test DELETE API via Rest Assured:

  • Set the Base URI
  • Specify the Endpoint (example: /users/2)
  • Use given() to prepare request
  • Use .when().delete() to send the request
  • Use .then() to validate the response (status code, etc.)

Expected Response from https://reqres.in/api/users/2:

The ReqRes API will respond with HTTP status code 204 No Content which indicates successful deletion, but no body is returned.


Maven Dependencies

<dependencies>
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>5.4.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230227</version>
    </dependency>
</dependencies>




Java Code using Rest Assured:

import io.restassured.RestAssured;
import io.restassured.response.Response;

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

public class DeleteUserTest {

    public static void main(String[] args) {

        // Step 1: Set Base URI
        RestAssured.baseURI = "https://reqres.in/api";

        // Step 2: Perform DELETE request and validate
        Response response = given()
                                .when()
                                .delete("/users/2") // Endpoint
                                .then()
                                .statusCode(204) // Assert expected status code
                                .extract().response();

        // Step 3: Print response for debugging (though it should be empty)
        System.out.println("Status Code: " + response.getStatusCode());
        System.out.println("Response Body: '" + response.getBody().asString() + "'");
    }
}


Code explanation:

1. Set the base URI
2. Perform delete request and validate the response server code
3. Print the server code and response body


Just to Inform:
  • statusCode(204) ensures deletion is successful.
  • The response body should be empty (""), as per REST standard for DELETE.


Suggested Posts:

1. Validate XML Schema in RestAssured
2. How to extract Response in Rest Assured by JSONPath
3. Test OAth2 in RestAssured
4. Validate Request and Response in POJO by RestAssured
5. How to Test Basic Authentication in RestAssured

How to Test a POST API by Rest Assured

 



What is a POST API?

  • A POST API is an HTTP endpoint that allows a client to send data to the server.
  • The data is usually sent in the request body in formats like JSON, XML, or form data.
  • Common uses of POST APIs:

Creating a new resource (e.g., creating a new user in a system).
Submitting forms (login, registration, etc.).
Sending files or data for processing.


How to Test a POST API in Rest Assured

When testing a POST API in Rest Assured, you typically perform these steps:

1. Set the Base URI
  • Define the API host (e.g., https://reqres.in).
2. Define the Request Body
  • Prepare the JSON (or other format) data that you want to send.
3. Send the POST Request
  • Use Rest Assured to send the request to the endpoint (e.g., /api/users).
4. Validate Response Status Code
  • Check if the response code is correct (usually 201 Created for a successful POST).
5. Verify Response Body
  • Ensure the response contains the expected data (like the new id or confirmation message).
6. Check Response Headers (Optional)
  • Validate Content-Type, Location, etc., to ensure proper response formatting.


To test a POST API using Rest Assured with a JSONObject in Java, follow these steps:










Step-by-Step Implementation

1. Add Rest Assured Dependency

<dependencies>
    <!-- Rest Assured -->
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>5.3.0</version>
        <scope>test</scope>
    </dependency>

    <!-- JSON Library -->
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20230618</version>
    </dependency>
</dependencies>


API to be tested: 

POST https://reqres.in/api/users


















Sample request body:

{
  "name": "Himanshu",
  "job": "QA Engineer"
}



Expected response (201 Created):

{
  "name": "Himanshu",
  "job": "QA Engineer",
  "id": "123",
  "createdAt": "2025-07-28T..."
}



3. Java Code to Test POST API using JSONObject

import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.http.ContentType;
import org.json.JSONObject;

public class PostAPITest {

    public static void main(String[] args) {

        // Step 1: Set Base URI
        RestAssured.baseURI = "https://reqres.in/api";

        // Step 2: Create Request Payload using JSONObject
        JSONObject requestBody = new JSONObject();
        requestBody.put("name", "Himanshu");
        requestBody.put("job", "QA Engineer");

        // Step 3: Make POST Request
        Response response = RestAssured
            .given()
                .contentType(ContentType.JSON)
                .body(requestBody.toString())
                .log().all()
            .when()
                .post("/users")
            .then()
                .log().all()
                .statusCode(201)
                .extract().response();

        // Step 4: Print Response Fields
        System.out.println("ID: " + response.jsonPath().getString("id"));
        System.out.println("Created At: " + response.jsonPath().getString("createdAt"));
    }
}



Code Explanation:

LinePurpose
RestAssured.baseURISets the base URL.
JSONObjectBuilds the JSON body using key-value pairs.
given().contentType().body()Prepares the request with headers and body.
post("/users")Sends POST request to the endpoint.
statusCode(201)Verifies the response status.
response.jsonPath()Extracts values from JSON response.



Sample Output:

Request method:	POST
Request URI:	https://reqres.in/api/users
Request body:
{
    "name": "Himanshu",
    "job": "QA Engineer"
}
Response Status Code: 201
Response body:
{
    "name": "Himanshu",
    "job": "QA Engineer",
    "id": "867",
    "createdAt": "2025-07-28T14:30:55.098Z"
}


Suggested Posts:

1. Test Digest Auth by RestAssured
2. How to extract Response in Rest Assured by JSONPath
3. Test PUT API in RestAssured
4. Overview of RestAssured Framework
5. How to Test Basic Authentication in RestAssured