Automating PUT Request using Rest Assured


In the previous post, we learned about Automating POST Request by sending object in the body of the request. I would highly recommend to read the previous tutorials before proceeding with this one. In the current post, we will study about Automating PUT request by using Rest Assured.

PUT request puts a file or resource at a precise URI, and exactly at that URI. If there's already a file or resource at that URI, PUT replaces that file or resource. If there is no file or resource there, PUT creates one. PUT request is used to update the existing records. In the body we can send string as well as Java object. But we always send Java object in body.

The db.json file before sending the PUT request is a follows:




Now let's see an example of sending PUT Request using Rest Assured.


import com.restapiclass.Posts;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import static io.restassured.RestAssured.*;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;


public class PutStatusCodeTest {

  @BeforeClass
  public void setBaseUri () {

    RestAssured.baseURI = "https://localhost:3000";
  }


@Test
  public void updateUsingPut () {
    
    Posts post = new Posts();
    post.setId ("3");
    post.setTitle ("Hello Bhutan");
    post.setAuthor ("StaffWriter");
    
    given().body (post)
    .when ()
    .contentType (ContentType.JSON)
    .put ("/posts/3");

  }
}

In the setBaseUri method, We are simply setting the default URI  to use in all of our tests. Now when we write out a test that calls an API (as we will do in the next step), we don’t have to type in the full address of the API. In this case, the baseUri is http://localhost:3000.

In the updateUsingPut method, we start with Given method and specify the data to be updated as an object of Posts class created in earlier tutorial in the body method. Under When we simply add a check ‘contentType(ContentType.JSON)‘ to make sure that the response we get is in JSON format and under PUT method we specify the path '/posts/3' where 3 is the id whose content is to be updated.


Now once we sent a PUT request to our API, in db.json file the data related to id:3 will be updated.


As you can see the parameters related to id:3 has been updated as per the PUT request.

In the next post we will study about Automating PATCH request using Rest Assured.

Comments

Popular posts from this blog

Extracting an XML Response with Rest-Assured