How to Make a POST Request with Rest Assured?

In previous post you've learned Rest API Testing using Rest Assured and in this below post you will learn How to Make a POST Request with Rest Assured library.In this below code uses requestSpecBuilder to make a post request. Parameter descriptions are listed below.

restAPIURL – URL of the Rest API
APIBody – Body of the Rest API. Example: {"key1":"value1","key2":"value2"}
setContentType() – Pass the "application/json", "application/xml" or "text/html" etc. headers to setContenType() method.
Authentication credentials – Pass the username and password to the basic() method or if there is no authentication leave them blank basic("","")

How to Make a POST Request with Rest Assured


public class RestAssured {


 @Test
 public void httpPostMethodTest() throws JSONException, InterruptedException {

  //Rest API's URL
  String restAPIUrl = "http://{RestAPIURL}";

  //API Body
  String apiBody = "{\"key1\":\"value1\",\"key2\":\"value2\",\"key3\":\"value3\"}";

  // Building request by using requestSpecBuilder
  RequestSpecBuilder builder = new RequestSpecBuilder();

  //Set API's Body
  builder.setBody(apiBody);

  //Setting content type as application/json
  builder.setContentType("application/json; charset=UTF-8");

  RequestSpecification requestSpec = builder.build();

  //Making post request with authentication or leave blank if you don't have credentials like: basic("","")
  Response response = given().authentication().preemptive().basic({
    username
   }, {
    password
   })
   .spec(requestSpec).when().post(restAPIUrl);

  JSONObject JSONResponseBody = new JSONObject(response.body().asString());

  //Get the desired value of a parameter
  String result = JSONResponseBody.getString({
   key
  });

  //Check the Result
  Assert.assertEquals(result, "{expectedValue}");

 }
}

1 comment: