Search⌘ K
AI Features

POST Request

Explore how to automate HTTP POST requests in REST API testing using Rest Assured. Understand posting with raw string bodies and Java POJOs. Learn to set headers, send data, and validate responses with status codes and JSON output for effective API test automation.

In this lesson, we will discuss two variations of the POST Request:

  1. POST with string body
  2. POST request using POJO (Plain Old Java Object) class

HTTP POST request automation

In this lesson, we will discuss two variations of POST Request.

Example 1 – POST with a string body

  • HTTP Method: POST
  • Target URL: http://ezifyautomationlabs.com:6565
  • Resource path: /educative-rest/students
  • Message body: As a String Object
  • Take a look at the code below:
Java
import static org.testng.Assert.assertTrue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.response.Response;
public class POSTRequestTest {
private static Logger LOG = LoggerFactory.getLogger(POSTRequestTest.class);
@Test
public void testPOSTStringBody() {
String url = "http://ezifyautomationlabs.com:6565/educative-rest/students";
LOG.info("Step - 1 : Target resource ( server ) : " + url);
String body = "{\"first_name\": \"Jack\", \"last_name\": \"Preacher\", \"gender\": \"Male\" }";
LOG.info("Step - 2 : Message body: " + body);
LOG.info("Step - 3 : Send a POST Request");
Response response = RestAssured.given()
.header("accept", "application/json")
.header("content-type", "application/json")
.body(body)
.post(url)
.andReturn();
LOG.info("Step - 4 : Print the response message and assert the status response code is 201 - Created");
response.getBody().prettyPrint();
assertTrue(response.getStatusCode() == 201);
}
}

Let’s understand the ...