How to test POST Request using Rest Assured

HOME

In the last tutorial, I have explained How to test GET Request using Rest Assured. In this tutorial, I will automate a POST Request using Rest Assured. I will verify the status code, line of Status, and content of the Response. To setup a basic Rest Assured Maven Project, click here and Gradle project, click here.

What is POST Method?

An HTTP POST method is used to create a new resource in the collection of resources with a request body passed as a JSON/XML or in a different format. If a resource is created successfully by the endpoint or server, it returns a status code 201( Created) , returning a Location header with a link to the newly-created resource with the 201 HTTP status. It may return 200 (OK) and 204 (No Content) status code as well based on how API is developed.

POST is neither safe nor idempotent. It is therefore recommended for non-idempotent resource requests. Making two identical POST requests will most-likely result in two resources containing the same information.

Below are the steps to test a POST Request using Rest Assured:

Step 1 – Specify the base URL to the RESTful web service using RestAssured class.

RestAssured.baseURI = "http://dummy.restapiexample.com/api/v1/create";

Step 2 – Every Request in Rest-Assured library is represented by an interface called RequestSpecification. This interface allows to modify the request, like adding headers or adding authentication details. Use the RestAssured class to generate a RequestSpecification.

requestSpecification = RestAssured.given();

RequestSpecification is imported from package:

import io.restassured.specification.RequestSpecification;

Step 3 – Set the content type to specify format in which request payload will be send to the server. Here, the Content Type is JSON.

requestSpecification.contentType(ContentType.JSON);

contentType is imported from restassured.http package:

import io.restassured.http.ContentType;

Step 4 – Pass Request Body as String.

requestSpecification.body(jsonString);

Step 5 – Send the POST request to the server and recieve the response of the request made by REST Assured. This response contains every details returned by hitting request i.e. response body, response headers, status code, status lines, cookies etc. Response is imported from package:

import io.restassured.response.Response;

Step 6 – To validate response like status code or value , we need to get reference of type ValidatableResponseValidatableResponse is an interface. A validatable response of a request made by REST Assured. ValidatableResponse is imported from package:

import io.restassured.response.ValidatableResponse;

PrettyPrint() – It print the response body if possible and return it as string. Pretty printing is possible for content-types JSON, XML and HTML.

Below is the example of testing a POST request in Non-BDD format where I have used ValidatableResponse for the assertion of status and status line and body of the Response.

public class POST_NonBDDDemo {

	RequestSpecification requestSpecification;
	Response response;
	ValidatableResponse validatableResponse;

	@Test
	public void verifyStatusCode() {

		String jsonString = "{\"name\":\"newapitest\",\"salary\":\"4000\",\"age\":\"29\"}";

		RestAssured.baseURI = "http://dummy.restapiexample.com/api/v1/create";

		// Create a request specification
		requestSpecification = RestAssured.given();

		// Setting content type to specify format in which request payload will be sent.
		requestSpecification.contentType(ContentType.JSON);

		// Adding body as string
		requestSpecification.body(jsonString);

		// Calling POST method
		response = requestSpecification.post();

		// Let's print response body.
		String responseString = response.prettyPrint();

		/*
		 * To perform validation on response, we need to get ValidatableResponse type of
		 * response
		 */
		validatableResponse = response.then();

		// Check status code
		validatableResponse.statusCode(200);

		// It will check if status line is as expected
		validatableResponse.statusLine("HTTP/1.1 200 OK");

		// Check response body - name attribute
		validatableResponse.body("data.name", equalTo("newapitest"));

		// Check response body - message attribute
		validatableResponse.body("message", equalTo("Successfully! Record has been added."));

	}
}

The below image shows the test result of the above test.

Test implemented in BDD Format

  1. equalTo is used for assertion, is imported from a static hamcrest package:
import static org.hamcrest.Matchers.equalTo;

2. given is a static import from package:

import static io.restassured.RestAssured.given;

Below is the example of BDD Test

public class POST_BDDDemo {
	ValidatableResponse validatableResponse;

	@Test
	public void createUser() {

		String json = "{\"name\":\"apitest\",\"salary\":\"5000\",\"age\":\"30\"}";

		// GIVEN
		validatableResponse = given()
				.baseUri("http://dummy.restapiexample.com/api")
				.contentType(ContentType.JSON)
				.body(json)
				
				// WHEN
				.when()
				     .post("/v1/create")
				     
				// THEN
				.then()
				      .assertThat().statusCode(200).body("data.name", equalTo("apitest"))
				      .body("message", equalTo("Successfully! Record has been added."));
		
		System.out.println("Response :" + validatableResponse.extract().asPrettyString());
	}

}

The below image shows the test result of the above test.

The above tests can be used in both Maven and Gradle projects.

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s