d

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore.

15 St Margarets, NY 10033
(+381) 11 123 4567
ouroffice@aware.com

 

KMF

How to Automate Restful APIs Using Jayway Library

Software APIs have been one of the most trending technologies. While most functional testing requires interaction with the user interface, API testing involves by-passing the user interface and communicating directly with an application server by making calls to its API. Successful web applications and mobile apps are all the results of the greatest API at the backend.

In agile methodology, most of the QA’s time is spent automating against the GUI using Selenium or any other framework. But in this article, we would look up the smart way to automate our APIs so that UI automation can be reduced a little and automation testing can be done more reliably.

Moving forward, let’s look at a very simple way to create an API and set up a JSON server. Below is the sample JSON named companies.json that we’ll be using in this article.

{
  "E-Commerce": [
    {
      "id": 1,
      "name": "Amazon",
      "ceo": "Jeff Bezos",
      "isGlobal": true
    },
    {
      "id": 2,
      "name": "Flipkart",
      "ceo": "Kalyan Krishnamurthy",
      "isGlobal": false
    }
  ],
  "Banking": [
	{
      "id": 1,
      "name": "JP Morgan",
      "ceo": "Jamie Dimon",
      "isGlobal": true
    },
    {
      "id": 2,
      "name": "Wells Fargo",
      "ceo": "Charles W. Scharf",
      "isGlobal": true
    }
  ],
  "Automobile": [
    {
      "id": 1,
      "name": "BMW",
      "ceo": "Harald Krueger",
      "isGlobal": true
    }
  ]
}

In this JSON file, we have collected the data in various industries like E-Commerce, Banking, and automobiles.

Since we now have a JSON file, we are ready to set up a JSON server.

JSON server is a simple project that helps set up a REST API with CRUD operations very fast.

JSON server is available as an NPM package; hence it is a prerequisite to have NPM installed.  Below are two commands to set up and start a JSON server:

  • $ npm install -g json-server
  • $ json-server –watch companies.json

There are a few parameters that we have used in the above second command for the sole purpose to start a JSON server. Parameter companies.json, supposed to be a file name containing our JSON structure. Further, we have used a parameter — watch to start the server in watch mode that means the server watches the file changes and manifests API accordingly.

Once your server gets started, the output would be as follows:

We can now open URL: http://localhost:3000/ on which the JSON server has been started by default to get the following view:

json server output

To see data of each industry, you can either click on the resources visible on the above page screenshot or redirect to the below URL:

  1. http://localhost:3000/E-Commerce
  2. http://localhost:3000/Banking
  3. http://localhost:3000/Automobile

If you are familiar with Postman, I suggest hitting below API endpoints with Postman before switching to API automation: 

GET    /Banking
GET    /Banking/{id}
POST   /Banking
PUT    /Banking/{id}
PATCH  /Banking/{id}
DELETE /Banking/{id}

Changes will be automatically saved to companies.json depending upon the JSON you give in the request body in case of POST, PUT, PATCH, or DELETE requests.

Note: Id is an integer that is a unique default identifier for the input JSON object.

API Automation

For the automation of APIs, we would be creating a Maven Project with the TestNG framework. In this article, we will be using a jayway-restassured library for automation. Below are a few dependencies that are required to be included in the pom.xml file. 

 <dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>6.14.3</version>
    <scope>test</scope>
</dependency>
    
    <dependency>
    <groupId>com.jayway.restassured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>2.9.0</version>
    <scope>test</scope>
</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>org.testinfected.hamcrest-matchers</groupId>
    <artifactId>core-matchers</artifactId>
    <version>1.5</version>
</dependency>

Get Request

GET request is one of the most triggered HTTP requests to retrieve data from a server for the specified resource. This request doesn’t change the state of resources and safely gives data in JSON format.

@Test(description = "Get API method", enabled = true)
	public void getAPI()
{
		
Response response = given()
				.param("isGlobal",true)
				.param("name", "Wells Fargo")
				.when()
				.get("http://localhost:3000/Banking");
		 
	Assert.assertEquals(response.getStatusCode(), 200,"GET API failed to respond");
	System.out.println(response.asString());						 		 			
	}

Output: 

output api method

Code Walkthrough

Using a jayway-restassured library, we have used different methods and interfaces in the above code. Like, Response is an interface and is used to record the Response of GET requests. As a method, we have used given() to start building the request part, param() to add request parameters when() to describe the request situation, and get() to perform a GET request to a path.

Furthermore, we have added assertions to verify the API status using the getStatusCode() method, which returns the status of the API response.

POST Request

Post is an HTTP method that is used to send new data to the API server to create or update a resource. The data to be sent is stored in the request body of the HTTP request. This means data sent to the POST method will not be visible in the URL as parameters are not sent with the URI.

@Test(description = "POST API method", enabled = true)
	public void postAPI(){
		
	Response response = given().
				body(" { "id": 2, "name": "Tesla", "ceo": "Elon Musk", "isGlobal": true }").
				when().
				contentType(ContentType.JSON).
				post("http://localhost:3000/Automobile");
		 				
	Assert.assertEquals(response.getStatusCode(), 201,"POST API failed to respond");
	System.out.println(response.asString());

	}

Output:

output test

New data must be added in companies.json file.

Code Walkthrough

In this Post request example, we are sending new data to our existing resource: Automobile. The body() method accepts the String type data such as JSON or XML that is to be sent as a request body. The ContentType method indicates the type of body in the POST request. The post() method has been used to perform a POST request to a path.

In the body() method, we have directly passed JSON in the form of String. However, if your JSON structure is too long, to avoid a cumbersome process, it is good to practice having a new JSON structure in a different JSON type file and pass the same file name in a body() method to get your JSON read from the JSON type file itself.

PUT Request

Similar to POST requests, the PUT request is also used to send data to the API server to create or update a resource. The difference between the POST and PUT requests is that PUT requests are idempotent, and POST requests are non-idempotent. That means invoking the same PUT requests multiple times will just overwrite the same resource state again and again and would not produce any different result.

PUT implies putting a resource and completely replacing whatever is available at a given endpoint URL with different data.

@Test(description = "PUT API method", enabled = true)
	public void putAPI(){
		
		 Response response = given().
					 body("{"id":2,"name":"Ebay","ceo":"Jamie Iannone"}").
					 when().
					 contentType(ContentType.JSON).
					 put("http://localhost:3000/E-Commerce/2");
		 				
	Assert.assertEquals(response.getStatusCode(), 200,"PUT API failed to respond");
	System.out.println(response.asString());	 
	}

Output:

New data must be added in companies.json file in E-Commerce second object.

Code Walkthrough

The methods are more or less the same as explained in the POST request. The only change of method is put() instead of post(). The put() method has been used to perform a PUT request to a path.

You would notice, POST request returns status code 201, and the PUT request returns status code 200. As per W3 protocols:

  • 200 : when an object is created and returned
  • 201 : when an object is created but only its reference is returned (such as an ID or a link)

PATCH Request

A PATCH request is used to make changes to the specific part of the resource. This request is generally triggered to make minor updates, and it’s not required to be idempotent. While the PATCH method is mostly used to make small updates, the PUT method is used to create a new resource or replace the existing resource with a new resource.

@Test(description = "PATCH API method", enabled = true)
public void patchAPI(){
		
		
		 Response response = given().
				 	body("{"name": "Fabric"}").
				 	when().
				 	contentType(ContentType.JSON).
				 	patch("http://localhost:3000/E-Commerce/1");
		 
	Assert.assertEquals(response.getStatusCode(), 200,"PATCH API failed to respond");	
	System.out.println(response.asString());	
	}

Output:

patch api output

Updated data must be added in companies.json file in the E-Commerce first object.

Code Walkthrough

The above code is mostly similar to the code written for POST and PUT requests. The only difference is that we have used the patch() method, which is used to perform patch requests to a specified path.

Always remember, as an output, unlike a PUT request, a PATCH request only updates the targeted location of the resource.

DELETE Request

As the name suggests, a DELETE request is made to delete the existing record from a particular resource. This request is one of the heavily tested requests since they remove data directly from the database and can change the server state. It requires an extra parameter in an endpoint URL that indicates the resource to be deleted.

@Test(description = "Delete API method", enabled = true)
public void deleteAPI(){
		
	Response response = given().
				when().
				delete("http://localhost:3000/Banking/1");
		 
	Assert.assertEquals(response.getStatusCode(), 200,"DELETE API failed to respond");	
	System.out.println(response.asString());		
	}

Output:

delete request output

 Record must be deleted from companies.json for Banking object one.

Code Walkthrough

The methods and interfaces that we have used in the DELETE request code are probably the same as what we have covered before. The delete() method has been used to perform delete requests to a path.

Response Time

Response time is the amount of time taken by a system to react to a sent request. When we automate APIs, we not only verify the HTTP status code for each request, but also we need to make sure that we are getting responses from the server in a sufficient time. Server response time as 200-350ms is considered fast, 351-700ms is average, and all the rest can be called slow. Below is the sample code to extract the server response time. The below code has been written for GET requests only. However, that can be used with all HTTP requests, i.e. POST, PUT, PATCH, and DELETE, by clubbing with the examples shown above.

@Test(description = "API Response Time", enabled = true)
public void responseTime(){
		
	Response response = given().
				 when().
get("http://localhost:3000/E-Commerce");
		 
	Long responseTime = response.
				then().
				extract().
				time();
				 		
	 System.out.println(response.asString());
	System.out.println("Response Time = " + responseTime + “ms”);
		 			 		
	}

Output: 

response time output

Conclusion

In this quick tutorial, we focused on understanding different Restful APIs. 

We have created our JSON structure and have set up the JSON server. With the running of the JSON server, we have implemented the automation of these APIs using a jayway-restassured library in the maven project. In API automation, we have covered the verification of HTTP status code along with the server response time.

So give this a try at your end, do not forget to hit the given API endpoints from Postman first. Performing API testing using Postman will make your basics more clear and will further make it easier for you to understand API automation.

Credit: Source link

Previous Next
Close
Test Caption
Test Description goes like this