Tuesday, July 23, 2019

REST Assured API Automation Setup and Understanding Basic


What is REST Assured?

REST assured is Java DSL  for simplifying testing of REST-based services built on top of HTTP builder, It supports POST, GET, PUT, DELETE, OPTIONS, PATCH, and HEAD requests and can be used to validate and verify the response of the request.


       1. Download the Java if you don’t have the java installed in your system using the following link. Java Download link

      2. Setup the environmental variable path in the system

      3. Download the eclipse from given link Eclipse Download
 
      4. Download REST assured jars from given link REST assured Jar links

      5. Setup Java Project in Eclipse and configure jars in the build path




Basic Program :-


package TestFramework;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

import org.testng.annotations.Test;



public class basics {

@Test
public void getPlaceAPI()
{
// TODO Auto-generated method stub

//BaseURL or Host
RestAssured.baseURI="https://maps.googleapis.com";

given().
       param("location","-33.8670522,151.1957362").
       param("radius","500").
       param("key","AIzaSyDIQgAh0B4p0SdyYkyW8tlG-y0yJMfss5Y").
       when().
       get("/maps/api/place/nearbysearch/json").
       then().assertThat().statusCode(200).and().contentType(ContentType.JSON).and().
       body("results[0].name",equalTo("Sydney")).and().
       body("results[0].place_id", equalTo("ChIJP3Sa8ziYEmsRUKgyFmh9AQM")).and().
       header("Server","pablo");

}

}

   
In the above example program,

We are using RestAssured.baseURI, RestAssured is the class which has the base URI ()  method, baseURI () method will accept a string, we need to pass the base part of API we need to automate in above example “https://maps.googleapis.com" is the base part of the API we are automating.

Before to analyze the remaining code of lines we need to know there are 4 blocks in API automation there are.

1. Given ()
2. When ()
3. Then ()
4. Extract ()



Given (): Given block is nothing but request head, as we discussed earlier different part of endpoint the request in that header, input parameters are sent and in Given block itself

            NOTE: All the parameters are sent in the Given block as Key and Value format, it may be POST or GET request, But the method used to pass parameters will be different will discuss in the next topic.

In the above example,

        We have Given () class which has the param () method, which accepts the value in Key and Value Format where both should be string data type.

        “Key”  value always will be the name of the Parameter input we are passing.
           
       “Value” value always will be the value we need to pass for that parameter input.

In the above basic program “Location” is an example for “Key” and  “-33.8670522,151.1957362”  is an example for “Value”.


When ():  When block always has the Resource part of the API request we are automating.
In the above example “/maps/api/place/nearbysearch/json” is resource, We call the get method to pass the resource API.


Then (): Then block is used to validate the response using assert () functions. This part of scripting is also called as validation

In the above basic program,
         
          We are validation response status, content type, name, place_ID, and server value is correct or wrong, If any one of the above is not matched with actual data we get any exception.
“java.lang.assertionerror”.  And test case will fail if any one of the assertions fails.

       NOTE: We can validate both “Body data” and “Header data”, just we have to call the respective method. Which are the body () and header ().


Extract (): Extract block always used to extract the response we got from the server, we can extract response writing below line code
Extract (). response ();

       NOTE: We can store response in Variable of the type response

        The response we get it will always be in raw format, so we need to convert the raw data to JSON or XML format based on the requirement. To follow the above scenarios  we have following steps

 
   We have to give a response in string format using the following line of code

                  String resstring = res.asstring();

   Where “res” is the variable name, In which we stored the response of extracted form extract method. asString () is a built-in method which will convert given data into the string format.
   
   Now, We have to convert the response which is in string format to the JSON format using the following line of code

            Jsonpath  js= new jsonpath (resstring);

    Where the JSON path is the inbuilt method which accepts the string value and converts the data into  JSON format and returns it back.

     Now our extracted data is converted to JSON format, We converted the data in JSON format because, If we want to integrate the two API request in one request where one API response value is input of another API in this scenario we need to extract the value which we need to pass as the response, We can’t do if the given response is String or Raw because we can’t traverse through response and fetch the value we need we can only do traverse if the data is in JSON format.

Now we will discuss about the different parameters we pass as input for an API request

There are 3 types of API request

   1.Path parameter
   2.Query parameter
   3.Header parameter

1. Path parameter: Parameter will be in request URL itself but these parameters will be separated by  “?” question mark symbol form API request link, these will be separated by forwarding slash (“/”)

           Ex: www.exaple.com/book/bookid.

To pass this type of parameter we can just use the prama () method.


2. Query parameter: Parameter will be in request URL but these parameters will be separated by “?” question mark symbol from API request link.

Ex: www.google.com/maps?place=0.2342

To pass this type of parameter we must use queryprama() method.

Header parameter:- Parameter will be in the header part of the API request,

  To pass this type of parameter we can just use prama () method.


NOTE: While calling POST API request, we need to be very clear sending the parameter. We have to use the respective parameter method to pass the parameter in the API.


Here, We discuss the REST API automation for POST request, the above example for GET request as it did not have a body part in the request

Here is sample code Automation code for POST API request,

package TestFramework;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import static org.hamcrest.Matchers.equalTo;

public class basics2 {


@Test
public void createPlaceAPI()
{
RestAssured.baseURI="https://maps.googleapis.com";
given().

queryParam("key","AIzaSyDIQgAh0B4p0SdyYkyW8tlG-y0yJMfss5Y").
body("{"+
  "\"location\": {"+
    "\"lat\": -33.8669710,"+
    "\"lng\": 151.1958750"+
  "},"+
  "\"accuracy\": 50,"+
  "\"name\": \"Google Shoes!\","+
  "\"phone_number\": \"(02) 9374 4000\","+
  "\"address\": \"48 Pirrama Road, Pyrmont, NSW 2009, Australia\","+
  "\"types\": [\"shoe_store\"],"+
  "\"website\": \"http://www.google.com.au/\","+
  "\"language\": \"en-AU\""+
"}").
when().
post("/maps/api/place/add/json").
then().assertThat().statusCode(200).and().contentType(ContentType.JSON).and().
body("status",equalTo("OK"));

// Create a place =response (place id)

// delete Place = (Request - Place id)


}
}


In the above Automation code and previously discussed automation code, there is the only difference is Body data of API we are passing in the request

Any POST API request always have the Body data to be passed, we pass the body data using the following method, body (String s); it is the inbuilt function which only accepts the String value as input parameter, In this case, we come across challenge How to pass the String which has the double quote as a parameter to a method which accepts the string as a parameter?  - Most commonly asked question in interviews.

We can handle the above scenario,

We need to add the forward-slash (/) in front of the double quote we have in a string value, it makes the java compiler to understand that double quote is a string value.


In the next blog, we will discuss the Optimization above-mentioned script with centralized data

                                                                                                       
                                                                                                               Thank you.

Thursday, July 11, 2019

REST Assured API Automation

 

  • Key points to know before testing  REST API 

1. How to send the Call to REST API?
2. What are Endpoints?
3. What are the types of REST request?
4. What is header/ Cookies?

  • End Points: Endpoints divided into the following parts

1.Base URL
2.Resource 
                 3.Parameters

1. Base URL: It is also known as host URL, The Website link itself is base URL.

Ex: https://www.google.com

2. Resource: It is mentioned after the Base URL in the link, which is the different module in the given host like
as above example in Google there are many modules, we have to write the module name
we want to hit.

Ex: https://www.google.com/maps,Here the “maps” is the resource we are using for Google or
we want to use the map module of the google website.

3. Parameters: These are the input values passed along the API call, To know what all parameters to be
passed for particular API, we need to go through the API doc they provided.
Every API we will have different parameters.  

Ex:  https://www.google.com/maps?place = ‘Bangalore’

In the above example we are passing the input parameter “Place“, 
it is one of the input to be passed according to the Google API Document 

NOTE: Parameters passed in two different ways, they are mentioned below

1. Parameters passed in the API URL itself.  
2. Parameters passed in the Body of the API. 

Above mentioned way depends upon the API request, we are calling to get the data 


There are 4 different types of REST API request can be used to communicate with Server,
they are mentioned below:


1.GET
2.POST
3.PUT
4.DELETE

Let's learn one by one,


1. GET: This type of request only used to retrieve or fetch the data from the Server.
It is more like asking a question or sending the query to the server, Once the server get the
GET request it analyses the request and sends the data in JSON or XML format.

In GET request, Input parameters passed in the API URL itself.


2. POST: This type of request used to add or create the data in the server, If the user wants to add the data to
existing server DB, he needs to call  POST request, When the server gets POST request it analyses
the request and create or add the data accordingly in the server DB and sends the
Response to the user in XML or JSON format.


In POST request, Input parameters passed in the Body of XML or JSON request,
nothing but passing the parameters in the body of the request.


NOTE: If we pass the required parameters wrongly, then the server will return the error message,
to get the correct response we need to pass the right parameters.


3. PUT: This type of request used to update the data already present in the server DB, It is also known as
a subset of POST request because If we can use the POST request itself to update the data in the
server DB, Hence In IT industry most companies only use the GET and POST
methods to communicate with the server.



In PUT request also we need to send the input parameters should be passed in the body of the API request.



4. DELETE: This type of request used to delete the data already present in the server DB,
it is also a subset of POST request as I have already told POST request is used to create,
update and delete the data from the server DB.

In DELETE request also we need to send the input parameters should be passed
in the body of the API request.


Headers: It is another part of the API request, headers are mainly used to Authentication and define
the content type we need to get the data.


Content-type: As mentioned above points the data will be received in XML or JSON format.

Hence there are two types of the format we can get data
1. XML
2. JSON

To make sure we want the data in the format we need it will be decided in the header of the API request,
in the header we mention the content type, the format which we need the response from the server 

Ex: Content type = JSON

In the above example, If we send the API request to the server, the server will first analyze the header of
the request first because header always has the major part of the request which is Authentication, once
it sees the content type has value JSON, Sever will understand that data it will send the response in
JSON format.


Authentication: This will always be part of request header, It plays an important role in API request,
As server will only process the request and send the data once the response is sent,
the system will keep track of the user recent query and verify the user.
the user who is accessing data is valid or intruder for that application
To prevent all this API request use the Authentication in the header of the request 

As Server receives the API request, It will authenticate the API request is form valid user or not,

We can use the  following way to authenticate 

1.Basic Authentication.
2.Digest Authentication.
3.OAuthentication 1.0
4.OAuthentication 2.0
5.Hawk Authentication
6.AWS signature

For currently, we are learning the only Authentication using the Header which is an easy way to do,
In our case, the API should have sent with X-token which is the randomly generated the token and
present in the server DB and also linked with one user.


We need the following scenario to explain the above point
  • Consider a User login into the Website we hosted, To login, Our Web app will call the Login API which needs two parameters
1. User name
2. Password and
3. UserID.

  • Once the Login API called the user is searched in Server DB and identify the User and validate the Username and Password sent by the Web app matches with the Username and Password linked with that userID
  • Once the Username and Password are matched, Server will create the hexadecimal token we called it as X-token or key, which always will be unique for every user when they log in every time they log in to the system and old x-token or key will be deleted automatically once they logged out or expire once the specified time period is over.
  • The above X-token is sent as the response for Login API and x-token get stored in the web browser as the Cookie which will store all session data in local memory for the web browser. 
  • Every time user make any request the API response will have the X-token in the player header, through x-token server identify the User is the valid user or not and also identify and remember the previous query the user had made to the server 
We can do the manual testing of REST API using the following API tools, 

1.Postman
2.Jmeter
3.SoapUI   
4.Katalon 


There are many tools available for manual testing one of the most popular and commonly used tool across
the industry is Postman. 


In the next blog,
We will discuss What is REST assured? and How to setup REST assured in the system?

                                                                                                                                     Thank you.