Show List

Testing PUT Request

Below is an example Java program that demonstrates how to use Rest Assured to test a PUT request to a REST API endpoint:


import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.response.Response; public class ApiPutTest { public static void main(String[] args) { // Set base URI of the REST API RestAssured.baseURI = "https://jsonplaceholder.typicode.com"; // Define PUT request body String requestBody = "{" + "\"userId\": 1," + "\"id\": 1," + "\"title\": \"Updated title\"," + "\"body\": \"Updated body\"" + "}"; // Send PUT request to /posts/1 endpoint Response response = RestAssured.given() .contentType(ContentType.JSON) .body(requestBody) .put("/posts/1"); // Get and print the response body String responseBody = response.getBody().asString(); System.out.println("Response Body:"); System.out.println(responseBody); // Get and print the status code int statusCode = response.getStatusCode(); System.out.println("\nStatus Code: " + statusCode); } }

In this example:

  • We set the base URI of the REST API using RestAssured.baseURI.
  • We define the JSON request body for the PUT request.
  • We send a PUT request to the /posts/1 endpoint using RestAssured.given().contentType(ContentType.JSON).body(requestBody).put("/posts/1").
  • We retrieve the response body and status code from the response object and print them out.

You can modify the base URI, request body, and endpoint according to the API you want to test. Make sure you have Rest Assured and its dependencies added to your project's classpath. Additionally, you may need to handle exceptions such as IOException or NullPointerException depending on your specific requirements and error handling strategy.


    Leave a Comment


  • captcha text