Automating PATCH Request using Rest Assured


In the previous post, we  learned about sending PUT request using Rest Assured. In the current post, we will learn about sending PATCH request using Rest Assured. I would highly recommend reading the previous tutorials before starting with this one.

The PATCH method is the correct choice when you're updating an existing resource - the group ID. PUT should only be used if you're replacing a resource in its entirety. Patch request is used when we want to update specific data related to that id.

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



Now let's look at an example of sending PATCH request

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

public class PatchRequestTest {

  @BeforeClass
  public void setBaseUri () {

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


@Test
  public void updateUsingPatch () {
    
    Posts post = new Posts();
    post.setId ("3");
    post.setTitle ("Hello Vietnam");
    
    given().body (post)
    .when ()
    .contentType (ContentType.JSON)
    .patch ("/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 updateUsingPatch method, we start with Given method and specify the data to be updated as an object of Posts class created in the earlier tutorial in the body method. We set ID and title using the setter method of Posts class and don't set the author. Under When we simply add a check ‘contentType(ContentType.JSON)‘ to make sure that the response we get is in JSON format and under PATCH method we specify the path '/posts/3' where 3 is the id whose content is to be updated. 



In the above example, only the title is updated and not the author in db.json file.

In the next post, we will study about automating delete request using Rest Assured.

Comments

Popular posts from this blog

Extracting an XML Response with Rest-Assured