Rest API Automation in Java - Post Method

Using Rest-assured and TestNG


In this post, we will learn to automate REST APIs using Rest-Assured library and TestNG. Rest Assured is a Java library using which we can test and validate the REST web services. Although Rest-assured provides its own validating mechanism(assertions for validating response) but we can combine Rest-assured with TestNG to get the best of both the libraries.



During the course of this tutorial, we will be using the following-



<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>3.1.1</version>
</dependency>

  • TestNG as testing framework
Automating Rest API HTTP Post method

The following code snippet uses requestSpecBuilder to create a post request. We have used the following parameters in our code, you need to set them as per your requirement-
  1. APIUrl - Set APIUrl variable with the URL of the Rest API
  2. APIBody - Set APIBody variable with body of the Rest API containing parameters e.g. {"key1":"value1","key2":"value2"}
  3. setContentType() - Pass the "application/json", "application/xml" or "text/html" etc. headers to setContenType() method
  4. Authentication credentials - Pass the username and password to the basic() method and in case of no authentication leave them blank basic("","")

The comments in the following code make it self-explanatory.