How to Test a PUT API by Rest Assured

 

To test a PUT API using Rest Assured in Java, you'll follow these steps:


What is PUT Request?

PUT request is used to update a resource on the server. For example, modifying a user's details.

The endpoint we'll use:
https://reqres.in/api/users/2 — This updates user with ID 2.


Steps to test PUT API using Rest Assured

  • Add dependencies (Maven or Gradle)
  • Set the Base URI
  • Create the JSON request body using JSONObject
  • Send PUT request using given()
  • Validate the response



Maven Dependency


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





Java Code using Rest Assured & JSONObject


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

import static io.restassured.RestAssured.given;

public class PutApiTest {

    public static void main(String[] args) {

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

        // Step 2: Create JSON body using JSONObject
        JSONObject requestBody = new JSONObject();
        requestBody.put("name", "Himanshu");
        requestBody.put("job", "Software Engineer");

        // Step 3: Send PUT request and get the response
        Response response = given()
                .header("Content-Type", "application/json")
                .body(requestBody.toString())
                .when()
                .put("/users/2")
                .then()
                .statusCode(200)  // Verifying status code
                .extract()
                .response();

        // Step 4: Print response
        System.out.println("Response Body:");
        System.out.println(response.getBody().asPrettyString());
    }
}




Code Explanation:


LinePurpose
RestAssured.baseURISets the base server endpoint
JSONObjectBuilds the request payload
given().header().body()Prepares the request with header & body
.put("/users/2")Sends PUT request to /users/2
.statusCode(200)Asserts response code is 200 OK
.response()Extracts full response
.asPrettyString()Converts raw response to formatted JSON string




Response:


{
    "name": "Himanshu",
    "job": "Software Engineer",
    "updatedAt": "2025-07-28T13:48:32.054Z"
}

No comments:

Post a Comment