Automating POST Request using Rest Assured - Part 1
In the previous post, we learned about how to install and configure the API Server on our local system. In this post, we learn to automate a POST request to API installed on our local system by sending a string in the body method.
Rest Assured supports all the HTTP methods like GET, POST, PUT and DELETE. Here GET stands for Read operation, POST stands for Write operation, PUT stands for Update operation and DELETE as the name suggests it stands for Delete operation.
Now let's look at an example of POST Request using Rest Assured
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import static io.restassured.RestAssured.*;
public class PostRequestTest {
@BeforeClass
public void setBaseUri () {
RestAssured.baseURI = "http://localhost:3000";
}
@Test
public void postString () {
given().body ("{\"id\":\"2\","
+"\"title\":\"Hello Mumbai\","
+"\"author\":\"StaffWriter\"}")
.when ()
.contentType (ContentType.JSON)
.post ("/posts");
}
}
In the postString method, we start with Given method and specify the data to be added as a String 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 POST method we specify the path '/posts'
Now once we sent a POST request to our API, the db.json file will have data related to id:2
So the data related to id :2 is added to db.json file.
In the next post, we will learn about how to send an object instead of string in body method of POST request.
In the next post, we will learn about how to send an object instead of string in body method of POST request.
Comments
Post a Comment