How To Automate API Requests Using Rest Assured And Jenkins

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated March 7, 2024

In this Tutorial we will Learn to Automate API Requests Using REST Assured while Executing Test Scripts Over Jenkins:

In the 2nd tutorial of the REST API Tutorial Series, we learned different types of response codes, REST requests, REST best practices and API testing using POSTMAN.

REST web services are becoming popular day by day because of their ease of development, implementation, access and then execution. On top of that, these are lightweight and do not have any strict standards to be followed.

=> Visit Here To Learn Jenkins From Scratch

Automate Rest API

However, when there is a larger number of services that exist, and need to be executed in every new build, then it becomes a nightmare for the tester and to the project cost. Again, some services are internal that are related to the project itself and some are build to be consumed by third parties.

So the idea of automation has come up. There are several tools available to automate the REST services such as-

  • vRest
  • HttpMaster
  • Parasoft
  • RestAssured

RestAssured is a popular automation tool among testers. Let us see why it is a preferred option.

Why RESTAssured?

  • It is open-source, hence any organization can use it for their project needs.
  • REST Assured is a Java library so it does not come as a GUI like other tools. It is a framework to test REST services in Java.
  • It provides a Domain-Specific Language (DSL) to create an automation script, uses any native language such as Java and tests the RESTful Web API.
  • It supports XML and JSON format for the Request, Responses.
  • It acts as a headless client.
  • We can customize the request which we are going to send to the server using this library.
  • Also, it can test a varied combination of complex business logic.
  • It is capable of fetching status code, responses, response body, headers from the server for the sent request.
  • It enables the BDD style of writing test script i.e. in the format of GIVEN-WHEN-THEN so that any business team member, especially from the non-IT background, can also view it and understand the logic and test coverage.

In this tutorial, we will be automating the requests which we created manually earlier in the first REST API tutorial through POSTMAN and we will also discuss a commercial tool named GITHUB.

Automating Web API Requests Using REST Assured

In this tutorial, we will be doing end-to-end automation i.e. creating a Java class and execute it from Jenkins.

Pre-requisites:

  • Intended recipients must have a working knowledge of Eclipse IDE, Maven, TestNG, ReportNG.
  • Recipients should also be aware of Jenkins.
  • Internet connection is required if we are accessing services deployed over the web. In case we are accessing services deployed locally, in that case, make sure the tester has the right.
  • If we are automating any commercial, secured sites, in that case, make sure the authorization token, API tokens, API Keys, etc are working properly and provided to the tester, who is currently automating the script.

Testing URL

Environmental Settings

#1) Install Eclipse IDE

First of all, we need to download the Eclipse IDE from the official website of Eclipse.

Then install the IDE. Set path, JAVA_HOME environmental variable correctly. Keep the JDK, JRE path handy for future use. Once Eclipse is installed, create/set a workspace and open the workspace.

In my case it is:

Select Workspace

#2) Create a Maven Project

Maven Project

Make sure you have configured the Maven home over Environmental variables.

#3) Add all relevant, necessary dependency, plugins relating to REST-ASSURED, TESTNG, REPORTNG to pom.xml.

Here is a sample pom.xml.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com</groupId>
  <artifactId>restapi</artifactId>
  <version>2.9.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>restapi</name>
  <url>http://maven.apache.org</url>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.11</version>
</dependency>
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>rest-assured</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>2.9.0</version>
</dependency>
        
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-junit</artifactId>
<version>2.0.0.0</version>
</dependency> 
        
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
 <version>2.4</version>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured-common</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
            <groupId>org.uncommons</groupId>
            <artifactId>reportng</artifactId>
            <version>1.1.4</version>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.testng</groupId>
                    <artifactId>testng</artifactId>
                </exclusion>
            </exclusions>
</dependency>
<dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
            <version>3.0</version> 
 
</dependency>  
  </dependencies>
  <build>
        <plugins> 
 
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.14.1</version>
                <configuration>
                    <arguements>
                        <argument>${env}</argument>
                    </arguements>
                    <properties>
                        <!-- Setting ReportNG listeners -->
                        <property>
                            <name>listener</name> 
                            <value>org.uncommons.reportng.HTMLReporter, org.uncommons.reportng.JUnitXMLReporter</value>
                        </property>
                    </properties>
                    <suiteXmlFiles> 
 
                           <suiteXmlFile>Tutorials.xml</suiteXmlFile> 
 
                    </suiteXmlFiles>
                    
                </configuration> 
 
           </plugin> 
 
     </plugins>
 </build>
</project>

#4) Add the required jars to the Maven projects build path.

Normally these are library file that comes under a REST-assured jar, TESTNG, REPORTNG. Even though we added the dependency, plugin over pom.xml file but still sometimes error comes hence we need to add these jars/libraries to build the path of maven project so as to prevent errors (if any).

Java Build Path

Java Build path Libraries

However, when we are creating Java projects instead of Maven projects, in that case, we need to keep these jars, libraries handy and use it as and when needed.

#5) Install JENKINS (On Windows)

Download the Jenkins from jenkins.io/download/.
Next, open the setup, follow the steps till it is installed properly.
Once installed we need to start JENKINS, we can do the same from a command prompt.

C:\Program Files\Jenkins> java -jar jenkins.war –httpPort=9090.

Started Initialization

Once the above message is displayed, then we need to wait for some more time to see the following message.

Jenkins Up Screen

As we can see the last message in the above screen where Jenkins is fully up and running, hence we can now launch Jenkins using the following URL.

http://localhost:9090/

The first time it may take time but then afterward it will be quicker. After that, we need to create a user.

User Creation

Password

Once the user is created, we need to relaunch Jenkins and access the UI with the password.

Once Jenkin is installed, we can install the plugins over Manage Jenkins > Global Tool Configuration (even during Jenkin installation).

Plugin

Creating Automation Script

#6) We can create a new JAVA CLASS and convert it to TESNG or directly create a TESTNG CLASS followed by creating a new XML file(testng.xml).

For simplicity, there are two Java Classes created

#1) Tutorial1.java  – This file contains usage of all the methods such as GET, POST, PUT, PATCH, DELETE, LOGREQUEST, LOGRESPONSE, ASSERT using a dummy testing URL https: jsonplaceholder.typicode.com.

Even though the URL behaves like an original URL by giving back such responses but actually over the server no modification is made. It is only to demonstrate the web services properties and reaction when they receive any request from a client.

#2)Tutorial2.java – This file contains the real-time example of GitHub where we will be reading the comment added to a gist.

Note: GitHub requires authentication hence we need to generate API token or basic authorization once we are logged in to GitHub – settings or else we can generate authorization token from POSTMAN itself

TESNG.XML

Here is the XML file which will execute both Tutorial1.java and Tutorial2.java

For demonstration purposes, I have excluded all methods to run and enabled only one GET method of Tutorial1.java to be executed. However, if we wish to see all the methods executed, then we have to replace <exclude> with <include> over TestNG XML file. In our case the TestNG file name is testng1.xml.

Now if we execute the above testng1.xml file over Eclipse then we will get the following console output.

[TestNGContentHandler] [WARN] It is strongly recommended to add “<!DOCTYPE suite SYSTEM “http://testng.org/testng-1.0.dtd” >” at the top of your file, otherwise, TestNG may fail or not work as expected.

[TestNG] Running:

D:\RestAssured\restapi\testng1.xml

***GET METHOD***
UserId – [1]id -[3]title – [ea molestias quasi exercitationem repellat qui ipsa sit aut]body -[et iusto sed quo iure
voluptatem occaecati omnis eligendi aut ad
voluptatem doloribus vel accusantium quis pariatur
molestiae porro eius odio et labore et velit aut]
***GET METHOD ENDS***

————————————————–

REST API Tutorials
Total tests run: 1, Failures: 0, Skips: 0

————————————————-

Here is the test result of the suite.

Results of Running Suite

Here is the default report generated by TestNG.

Test Output

Here is the report generated by ReportNG.

Test Results Report

Since we have already configured ReportNG, hence we can expect a clear view of the total passed, failed count as above.

Executing Test Scripts Using Command Prompt

  • We need to start the command prompt
  • Set the working directory as the workspace location
  • Find the bin/target location
  • Find/create library location
  • First, we need a set, the directory where the project exists. In my case it is D:\RestAssured\restapi
  • Java – keyword
  • cp – It is the classpath, means the path in which the Java class exists in the project
  • Target – It is the same as the bin folder when we are working on a Java project. Since we are working on the Maven project, hence we will have this folder. Under this folder, we can have, two more folders: classes, test-classes. The actual Java class shall exist among these two folders
  • Lib – This folder will contain all the jars which we have used while executing the test script from Eclipse. In some cases, the folder might not be present. Hence, we may need to create a folder and keep all the jars, executables, etc. inside it.
  • org.testng.TestNG testng1.xml – This is like a syntax. The last part is testng1.xml is the resource file of TestNG, which will be called to execute the desired test scripts

The complete command will be

java -cp target/test-classes;target/Classes;lib/* org.testng.TestNG testng1.xml

After that press enter

testing install

Note: We can see the bin folder while we working on a Java project. However, if we are working in a Maven project then we will have a target folder and normal classes, the test-classes folder will be present under it.

Creating BAT File And Execute Test Scripts

Instead of opening the command prompt and running the above command to execute the test script, we can keep the command in a text file and while saving it gives it a name like,

“run.bat”  [make sure you keep the “” around run.bat]

Here is how it looks once it is created.

Windows Batch File

Now double-click on “run”

The command prompt will open and it will execute the test script and once the execution completes, the command prompt gets closed.

Run Bat Execution

Integrating JENKINS With Maven, Java

We need to make 4-5 configurations at Jenkins to integrate it with Maven, Java and execute the same.

Once we log into Jenkins,
Goto Manager Jenkins >> Global Tool Configuration

set JDK installation path

Global Tool Configuration

Note: Make sure Jenkin’s version supports JDK/Java version. Jenkins version 2.73 requires at least JDK/JAVA Version 1.8 or else it will create problems while executing the test scripts.

Set the Maven installation path

Maven Installation Path

After that, Goto Manager Jenkins >> Configure Systems

Set Environmental variable path

Environment Path

Next, Create a New Item

We need to click on create a new link, specify the name for the job, select the type of project as Freestyle. No need to worry about other things as of now.

Jenkins Start

Once the job is created it will look like this.

Jenkins job

Now click on the job

Follow the below steps:

  • Click on the configure link on the left-hand side panel.
  • Scroll down the General tab and click on the Advanced button.
  • Select custom workspace checkbox and specify the project folder location.

Custom Workspace

After that

  • Scroll down more to Build Triggers
  • Select Build periodically checkbox
  • Set some time as mentioned below

Scheduling

Scroll down, set the name of Build. In our case, it is an executable Windows batch command.

It is in the same location where we have kept run.bat file earlier that is D:\RestAssured\restapi folder

Build

Save all the above changes made so far.

Now, wait for the cron job to run. We can see the build is initiated.

Jenkins Job

Once the build is executed successfully, next we need to click on the build # 20 as specified in the above image.

Click on the Console Output link in the left panel.

Now we should be able to see the following output.

Console Output

Conclusion

REST ASSURED is a very useful JAVA library to automate REST API’s irrespective of the language. It has many inbuilt options. Also, it has many versions with interesting functions, options included in it. It supports many formats as Requests such as XML, JSON, etc.

In this tutorial, we explained how to automate API Requests using RESTAssured while executing test scripts using Jenkins. We also explained why Rest Assured is a better choice to automate API Requests.

=> Explore The Simple Jenkins Training Series Here

Was this helpful?

Thanks for your feedback!

Leave a Comment