Where we learn technology

Month: November 2020

Scrum 2020 Guide — New Changes

                          SCRUM GUIDE 2020 UPDATES

 

CELEBRATING 25 YEARS OF SCRUM


It’s been 25 years since the launch of the Scrum Guide. With contributions from the Scrum community, Dr. Jeff Sutherland and Ken Schwaber have made updates to make it crisper, leaner and more transparent.

HTTP GET method using RestAssured

Get Request And Response
~Image Source : google / sashido.io

  1. Introduction

In this article, we are going to learn about the Get Request in detail, in addition to that, we will also learn how to validate Get Response using RestAssured.

2. Writing Get Method:

Let’s first get started with the simple example – Fetch user details and handle the response:

Assume application is up and running , let’s perform some action using when()

As we can see return type of when() is RequestSender ~https://javadoc.io/doc/io.rest-assured/

and RequestSender Interface Implements Classes as:RequestSpecificationImplTestSpecificationImpl

And in RequestSpecificationImpl class we have below methods such as get() :

Get Methods

Now, Let’s write the Get Method Code:

package com.restassured.testcases;

import static io.restassured.RestAssured.given;

import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.testng.annotations.Test;

/**
 *
 * @author Mandeep Kaur
 *
 */
public class SampleGetTest {

   @Test
    public void getTest() {

        /*
         * given application is up and running and performing the GET request with get(URL)
         * and printing the response 
         *
         */
        Response response =given().header("authorization", "Bearer 0431655cfe7ba40a791e0ce32d83ad33363348919c11627f409a3228f205e19f").when()
                .get("https://gorest.co.in/public-api/users");

        //Printing the response
        System.out.println(response.asString());
} }

In the above code ,it is clearly seen that we need header in order to execute get request and it takes key-value pair where Key as authorisation and value as Bearer access_token , get (URL ) and simply print the response and output will be like below and stored in response object.

User details are coming in response what’s more the details of test cases if it’s passed, failed depends on the test case written:

Output on the console and test case is passed and marked as green.

In order to validate status code , below code needs to be executed:

package com.restassured.testcases;

import static io.restassured.RestAssured.given;

import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.apache.http.HttpStatus;
import org.testng.annotations.Test;

/**
 * @author Mandeep Kaur
 */
public class SampleGetTest {

    @Test
    public void getTest() {

        /*
         * given application is up and running and performing the GET request with get(url)
         * with header then status code should be 200 OK
         *
         */
        given().header("authorization", "Bearer 0431655cfe7ba40a791e0ce32d83ad33363348919c12327f409a3228f205e19f").when()
                .get("https://gorest.co.in/public-api/users").then().assertThat().statusCode(HttpStatus.SC_OK);
    }
}

It can be inferred from the above code, if expected code is 200 ok then to validate it , we can use .assertThat and statusCode: HttpStatus.SC_OK without using 200 hard code value as it is, we can use HttpStatus interface variable from package org.apache.http; Similarly, the other statuses from Interface HttpStatus can be fetched like below:

Since, we have validated the status code, Let’s validate the response content also content level validation. Once we received the response , how we will validate that the content is proper or not ?

So, rest assured uses hamcrest Framework for validation.

Inside org.hamcrest package there is a class called Matchers and this class contains all the methods which we can be used for our validation purpose. Below are the methods of Matchers class and you can navigate here to learn more about Matchers class :

Go to Library org.hamcrest > Matchers Class> Methods

Matchers Class under org.hamcrest package

Let’s see the below code:

package com.restassured.testcases;

import static io.restassured.RestAssured.given;

import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.testng.annotations.Test;
import static org.hamcrest.Matchers.*;

/**
 * @author Mandeep Kaur
 */
public class SampleGetTest {
    @Test
    public void getTest() {

        /*
         * given application is up and running and performing the GET request with get(url)
         * Then response should have first email as given below
         */
        given().header("authorization", "Bearer 0431655cfe7ba40a791e0ce32d83ad33363348919c11627f409a3228f205e15f0394504395435").when()
                .get("https://gorest.co.in/public-api/users").
                then().
        body("data.email[0]",equalToIgnoringCase("dhawan_dharani@macejkovic.co"));


    }
}

After hitting the get endpoint , in the body we are validating whether the first email in our response matches to the given email given above in the code and here equalToIgnoringCase comes from the matches Class of hamcrest framework. what it does is where both actual value is equal to expected value irrespective of case.

If both the values matched we will get our test case passed otherwise it will failed as actual value is not getting matched with expected value.

Here’s the json response , for which our code matched perfectly:

Json Response

If not matched the expected value, then we will get the error as below:

and if multiple values to be validated , we can validate like below using comma  :

By now , You must be wondering why did i use data.email[0] for this we need to learn Json Path.

And another way of validating it with hasItem method of hamcrest and if it list needs to be validated then hasItems method will be used:

HasItem Method

hasSize to use when to check how many element a particular json array contains. For Example:

 "data": {
        "data1":[
            "id": 6,
            "name": "Dharani Dhawan",
            "email": "dhawan_dharani@macejkovic.co",
            "gender": "Female",
            "status": "Active",
]}

Now this contains 5 elements so size will be 5.

and in body we can assert :

.body(“data.data1”,hasSize(5));

3. JsonPath Class :

Another way of validating the response with JsonPath Class:

JsonPath class comes from the package

package io.restassured.path.json;

Let’s see the below code to gain deep understanding of it :

Extracting Values from jsonPath

package com.restassured.testcases;

import static io.restassured.RestAssured.given;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import org.testng.Assert;
import org.testng.annotations.Test;
import static org.hamcrest.Matchers.*;

/**
 * @author Mandeep Kaur
 */
public class SampleGetTest {
    @Test
    public void getTest() {

        /*
         * given application is up and running and performing the GET request with get(url)
         * Then response should have first email as given below
         */
       String resp= given().header("authorization", "Bearer 0431655cfe7ba40a791e0ce32d83ad33363348919c11627f409a3228f205e15f84985934850948")
               .accept(ContentType.JSON)
               .when().get("https://gorest.co.in/public-api/users").
                thenReturn().asString();

        JsonPath jsonpath= new JsonPath(resp);
        Assert.assertEquals("dhawan_dharani@macejkovic.co",jsonpath.getString("data.email[0]"));
    }
}

In this code, we fetched the response and store it in string variable.

Now, this variable needs to be passed as a JsonPath constructor, once this is done

we need to use testNg assertions to check our actual response is matched with expected Response.

Actual Value : given above as email

and jsonpath.getString for fetching the value of particular  Key:

data.email[0] : means Json Object starts with label data and email is comes under that label and JsonPath is same like Xpath where we transverse from root element to parent /sibling so on.

Since we need out first value to be matched me just used email[0].

To fetch int or other values it can be fetched like this :


Fetch values from jsonPath

4.Conclusion:

To conclude, We learnt to write our very first get Request Method and tried to validate our response with hamcrest framework and jsonPath Class .

Blog Contributors:

Author:  Mandeep Kaur
Mandeep, having 5+ years of Testing experience in automation using Selenium (Java). Expertise in API and Performance testing using JMeter.
https://www.linkedin.com/in/mandeepkaur93 
 
Reviewer: Naveen Khunteta 
https://www.linkedin.com/in/naveenkhunteta

 

 

 

 

Introduction To Rest Assured

1. Overview :

In this article, we will learn about automating our first API using Rest Assured and various terms linked with API.

2. API

Before proceeding any further , let’s try to understand what is API .

  • API: Application Programming Interface is nothing but public functions that can be called and executed by other programs, these other programs can be programs running in the same computer or those running in a different computer altogether.

Why do we need API or what does it offers :

  1. Abstraction 
  2. Contractual Obligations between client and backend

Let’s try to understand with the help of an example: 

Consider an ATM Machine, you are provided with multiple options such as checking account balance, cash deposit or withdrawal and statement, etc. So here you get all things by a push of few buttons.

Here APIs  play a Key Role in abstracting you from the backend services. Also performing any operations such as cash withdrawal you need to provide your ATM pin and the amount to be withdrawn.

The withdrawal would be allowed only if your pin is correct and have sufficient balance money in your account and it is within the bank transactional limit for the day. So these are some business rules defined and these are nothing but contractual obligations that an API defines and that has to be fulfilled.

So, in short, if both the business and data logic can be re-used in some other application. Then this application is called a web service.

3. Web Service:

It is an interoperable software system designed to support machine-to-machine interaction over a network. The three necessary conditions for any web application to become a web service:

  1. Interoperability: Any Java, DotNet, PHP, or C++ application, etc.., should be able to interact with the web application.
  2. Application-to-application interaction: For example, Jet Airways in its web application uses a different bank’s payment gateway to make payments. Here, banks have extended their applications over the network to be accessed by the jet airways application. Thus, the bank application is acting as a web service.
  3. Communication must be over a network

Now that you have understood the web service and API, the next important term you need to understand is the API endpoint

  1. It is a location from which an API can access the resource that it needs to carry out the functionality.
  2. It is a unique URL for communications between the client-side and server-side.

By now you have understood that web services are capable of communicating with web applications with the help of API endpoints.

Now the question is what does this API endpoint contain that makes any web server understand the requests from the UI and how to respond back?

The two things that make it possible are the request and response that is passed with every API call.

So now it’s imperative to understand how request and response exchange takes place between a client (Browser) and a server

You must have heard the terms SOAP and Rest, Let’s try to understand these first in detail:

4.SOAP Architecture:

So today many applications built in many programming language . For example there is web applications designed in JAVA, some are in .dot net and some in PHP.All these 

  • Application collect and store data, and this data needs to be exchanged among different applications.
  • But this exchange among these heterogeneous applications would be very complex.
  • So, one of the methods to combat this complexity is to bring a common language which is XML i.e. Extensible Markup Language
  • But there for no specific standard on how to use XML across all the programming language for data exchange

So this is where SOAP or Simple Object Access Protocol comes into the picture.

Here are a few reasons for using SOAP architecture:

  1. SOAP is considered a light-weight protocol that is used by applications for data exchange. Also, since SOAP is particularly based on XML, which in itself is a lightweight data exchange language, so it falls in the same category as a protocol.
  2. SOAP is designed to be platform and operating system independent. It can work with programming languages on both Windows and Linux platforms.
  3. It is based on the  HTTP protocol, which is the default protocol used by all web applications. Therefore, there is no customization required to run the web services built on the SOAP protocol to work on the World Wide Web.
  4. It helps in Exposing business functionality over the internet.

 Some limitations with SOAP architecture such as:

  1. The HTTP protocol is not used to its full extent.
  2. A resource representation is done only in XML which is fast, but still can be considered slower than many of its competing technologies such as JSON.
  3. Working with SOAP requires you to write a proper XML structure almost every time, even for extremely simple tasks. This makes your work lengthy and a bit complex.
  4. The above-mentioned limitations can overcome with the introduction of REST(Representational State Transfer) architecture.

5. Rest Architecture:

Let’s look at some characteristics of the REST architecture:

  1. It makes the best use of the HTTP protocol. The request and response sent are proper HTTP request and response. So, the request contains proper HTTP methods while the response contains proper status codes.
  2. It is a style for designing loosely-coupled web services.
  3. It relies on the stateless, client-server protocol, for example, HTTP. So, it does not store any client’s session on the server-side and thus making the REST APIs less complex to develop and maintain.

6. HTTP Protocol:

We have talked a lot about HTTP protocol, but we still don’t know what exactly is this HTTP or even protocol for that matter. 

So, whenever you enter any URL in the address bar of your browser, the browser translates that URL into a request message according to the specified protocol and then sends it to the server.

There are many predefined HTTP methods that can be used while sending HTTP requests.
Most common HTTP methods:

  1. GET :asks the server to retrieve a resource. You can think of a resource as some data or file on the server
  2. POST : asks the server to create a new resource
  3. PUT: asks the server to update a resource
  4. DELETE: asks the server to delete a resource
  5. PATCH: used to update a portion of an already existing resource

Then there are two different categorisation of HTTP methods:

  1. Safe: Safe methods are those that can be cached and prefetched without any repercussions to the resource. This means that there is no change expected in the resource by the client. So, GET is safe, while PUT, POST, DELETE PATCH are not.
  2. Idempotent: An idempotent HTTP method is one that if called many times will provide the same outcome. It does not matter if the method is called only once or multiple times. The result will always be the same. GET, PUT, DELETE methods are idempotent.

The response from the server is accompanied by a status code. This status code is important as it tells the client how to interpret the server response. Here are some of the common status codes –

  1. 1XX – informational
  2. 2XX – success
  3. 3XX – redirection
  4. 4XX – client error
  5. 5XX – server error

Some of the common HTTP status are:

  1. 201 (CREATED)
  2. 200 (OK)
  3. 401 (UNAUTHORIZED)
  4. 403 (FORBIDDEN)
  5. 400 (BAD_REQUEST)
  6. 404 (NOT_FOUND)

Figure: Sending a Request and getting the Response

Further, you can read about what happens when you type a URL and press enter.

https://medium.com/@maneesha.wijesinghe1/what-happens-when-you-type-an-url-in-the-browser-and-press-enter-bb0aa2449c1a

Till now we have learned about API, Web Services, SOAP and Rest, HTTP protocol, and methods, Now it’s the perfect time to know about Rest Assured.

7.Rest Assured:

  • REST Assured is an open-source Java library for validation of REST web services.
  • It is flexible and easy to use and supports all the Http Methods such as GET, POST, PUT, etc.
  • It supports BDD (Behavior-Driven Development) by using test notation, Given, When, and Then, which makes the tests human readable.
  • Rest Assured API uses the “Hamcrest” framework for validation.Which we will learn it in detail

8. Creating a simple Rest Assured Program:

Pre-requisites:

JDK 8 , Maven, Eclipse IDE

Let’s get started by creating the first project. Open Eclipse IDE and create a new project.

  1. Click on new –> Maven Project → create simple project → Next

2. Provide group id and Artifact id and click on finish:

Now , configure testNg and Rest Assured library in your pom File:

Once , libraries are added then create a class under src/test/java and create a test method in it:

Here’s the code:



package com.restassured.testcases; import org.testng.annotations.Test; import io.restassured.http.ContentType; import static io.restassured.RestAssured.*; /** * * @author Mandeep Kaur * */ public class SampleTest { @Test public void sampleLogin() { /* * Given application is up and running When i perform the GET request using the * given url Then the status code should be 200 Ok And the response body should * be in Json Format * */ given().accept(ContentType.JSON).header("user-key", "cde67df2673438bb2fae8dc7e205e98451903940394343").when() .get("https://developers.zomato.com/api/v2.1/categories").then().statusCode(200); } }  
  • Before concluding let’s understand few above terms quickly:

    • Rest Assured framework follows the BDD approach.
    • Given keyword defines the precondition
    • When keyword defines the action to be performed
    • Then keyword defines the outcome of the previous step
    • And keyword defines the additional outcome.
    In the above program, the Given application is up and running, the header is passed with a valid user key when performing the GET request using the given URL Then the status code should be 200 Ok And the response body should be in JSON Format (ContentType.Json)

and now run the project using mvn install command and output will be displayed as:

Conclusion:

To encapsulate, we have learned about API and it’s various terminologies, also created our first rest assured test 🙂

Blog Contributors:

Author:  Mandeep Kaur
Mandeep, having 5+ years of Testing experience in automation using Selenium (Java). Expertise in API and Performance testing using JMeter.
https://www.linkedin.com/in/mandeepkaur93
 
Reviewer: Naveen Khunteta 
https://www.linkedin.com/in/naveenkhunteta