How to Test a PUT Request Using Rest Assured

In REST API testing, a PUT request is used to update an existing resource. When you send a PUT request to a server, you are asking it to update a specific resource at a specified URI, often with a modified JSON or XML payload. Rest Assured, a popular Java library for testing REST APIs, makes it easy to automate this process and validate responses.

In this blog post, we’ll walk through the basics of setting up and testing a PUT request using Rest Assured, covering the following steps:

  1. Setting up the project with Rest Assured
  2. Writing a PUT request test
  3. Validating the response status and content
  4. Running the test

Let's get started!

1. Setting Up the Project with Rest Assured

To use Rest Assured, ensure your project is set up with the necessary dependencies. If you're using Maven, add the following dependency to your pom.xml:

<dependency>

    <groupId>io.rest-assured</groupId>

    <artifactId>rest-assured</artifactId>

    <version>5.3.0</version>

    <scope>test</scope>

</dependency>

2. Writing a PUT Request Test

Assuming we have an API endpoint for updating user data, let's say:

PUT https://api.example.com/users/{userId}

This endpoint updates user details based on a unique user ID. The PUT request might require a JSON payload in the request body, which specifies the updated information.

Let’s create a sample test to update a user's details using this endpoint. In our example, we’ll assume we are updating a user's name and job.

Here's a step-by-step test using Rest Assured:

import io.restassured.RestAssured;

import io.restassured.http.ContentType;

import io.restassured.response.Response;

import org.testng.Assert;

import org.testng.annotations.Test;


public class PutRequestTest {


    @Test

    public void testUpdateUser() {

        // Define the base URI

        RestAssured.baseURI = "https://api.example.com";

        

        // Specify the user ID to update

        int userId = 101;


        // Define the updated JSON payload

        String requestBody = "{\n" +

                "    \"name\": \"John Doe\",\n" +

                "    \"job\": \"Senior Software Engineer\"\n" +

                "}";


        // Send PUT request

        Response response = RestAssured

                .given()

                .contentType(ContentType.JSON)

                .body(requestBody)

                .when()

                .put("/users/" + userId);


        // Print response for debugging purposes

        System.out.println("Response: " + response.asPrettyString());


        // Assert the status code is 200

        Assert.assertEquals(response.getStatusCode(), 200, "Status code should be 200");


        // Optional: Validate response body contents

        String updatedName = response.jsonPath().getString("name");

        String updatedJob = response.jsonPath().getString("job");


        Assert.assertEquals(updatedName, "John Doe", "Name should be updated to John Doe");

        Assert.assertEquals(updatedJob, "Senior Software Engineer", "Job should be updated to Senior Software Engineer");

    }

}

In this code:

  1. Base URI: We set the base URI for the API to https://api.example.com.
  2. User ID: Specify the user ID in the endpoint URI to target the correct resource.
  3. Request Body: We define the JSON payload as a String, which includes the updated name and job.
  4. PUT Request: Use the .put() method to send a PUT request. We provide the request body using .body() and set the content type to JSON with .contentType(ContentType.JSON).
  5. Response Assertions: Verify that the status code is 200, indicating a successful update. We also check that the name and job fields in the response match the expected values.

3. Validating the Response Status and Content

Response validation is crucial in API testing. In the example above, we check:

  • Status Code: We use Assert.assertEquals() to confirm the response status code is 200, which indicates success.
  • Response Body: We use JSONPath to extract and validate specific fields from the response, ensuring the updated values are returned correctly.

4. Running the Test

To run the test, ensure you have set up your project to execute TestNG tests (if using TestNG). You can run the test class from your IDE or by running a Maven command:

mvn test

This command executes the test, and you should see an output indicating whether it passed or failed. Check for a successful 200 status code and verify that the response body matches your expectations.

Additional Validation Tips

  • Header Verification: Check headers like Content-Type, Cache-Control, etc.
  • Negative Testing: Test invalid payloads or incorrect user IDs to ensure the API responds with appropriate error messages and codes.
  • Response Time: You can also verify that the response time is within acceptable limits, especially for high-traffic APIs.

Followers