Where we learn technology

Tag: RestAssured

API/WebServices – BackEnd Manual & Automation Testing – Regular Batch – 11th July 2024 – 8 PM IST / 10:30 AM EST / 7:30 AM PST)

WebServices – Back End API Manual & Automation Training Course Content

Starting Date: July 11th, 2024

API Testing Training/Boot Camp:

The API testing batch/boot camp training for API/WebServices – Back End Manual & Automation Testing is a crucial training for individuals who want to enhance their skills in API testing. This training will cover essential topics related to API testing such as HTTP methods, RESTful APIs, JSON/XML, authentication, authorization, error handling, and much more. Candidates will learn both manual and automated testing methods for APIs.

Who can attend this training?

This training is perfect for software testers, quality assurance engineers, developers, and anyone interested in gaining knowledge and skills in API testing. Candidates will learn how to test APIs effectively, identify defects, and ensure that APIs are functioning as expected.

Additionally, this training will help individuals gain a competitive advantage in their careers by acquiring new skills and knowledge.

Why should I join this?

By attending this training, individuals will be better prepared for API testing interviews as they will have a solid understanding of API testing concepts, methods, and tools. They will be able to apply their knowledge to real-world scenarios and will have hands-on experience with various testing tools used in the industry. Overall, this API testing batch/boot camp training is an excellent investment for individuals looking to enhance their career opportunities and take their skills to the next level.

Next Batch Starting from: 11th July, 2024

Duration: 9-10 Weeks

Location: Online (zoom meeting) 

Duration: 3 days in a week (1.5 hrs) – Mon – Wed – Thursday

Timings

    • 8:00 PM IST (Indian Time)

    • 10:30 AM EST (USA Eastern Time)

    • 7:30 AM PST (USA Pacific Time)

    • 9:30 AM CST (USA Central Time)

    • 3:30 PM UK TIME

Registration Fee: For Candidates in India : 3000 INR

For Candidates in USA/UK/NZ/AUS/Europe : 55 USD

Remaining Course Fee

    • 12000 INR (For Candidates in India)

    • 200 USD (For Candidates in US/UK/NZ/AUS/Europe)

Note:

    • There will be 2 demo sessions. If you don’t want to proceed with the training, full Registration amount will be refunded back to you.

    • After 2 demo sessions, remaining amount (12000 INR/200 USD) must be paid accordingly.

    • For any query, whats app at: +91-9902233400.

 
Here I’m sharing the payment details. Please send me the screenshot of receipt once you make the payment without fail. 
You need to mail me at : naveenanimation20@gmail.com

 Payment Options:

CANDIDATES IN INDIA:
1. Pay by Credit/Debit Card:
If you want to use credit card/debit card, please use this secured stripe payment link:

REGISTRATION FEE (3000 INR):
https://buy.stripe.com/28obL2bjD6Ww5RC4hC

REMAINING FEE(12000 INR):
https://buy.stripe.com/4gwcP60EZ4Oocg015j

Or you can pay total fee (15000 INR):  
https://buy.stripe.com/00g16o3Rb3Kk93O9BR
2. BANK TRANSFER:

Bank Details:
Full Name: NAVEEN KHUNTETA

Payee name: NAVEEN KHUNTETA

Name of the Bank: ICICI bank

Address of the Bank: Bhandarkar Road, Pune

Bank Account Number: 624001553272

IFSC Code(11 Digit Code): ICIC0006240

3. Pay by GPay/PhonePe/Paytm/UPI:

ph: 9902233400 / 9828866542
======================================
CANDIDATES IN USA/CANADA/UK/EUROPE/AUS/OTHERS:
1. If you want to use credit card/debit card, please use this secured stripe payment link:
REGISTRATION Fee (55 USD):
https://buy.stripe.com/5kA5mEgDX4Oodk44hD
Remaining Fee(200 USD): 
https://buy.stripe.com/fZe5mEfzTeoY6VGdSe
You can pay full amount (255 USD):
https://buy.stripe.com/3cscP63Rb0y84Ny15t
2. Bank Transfer:

Please find below bank details. You can make the transaction directly to the given account or make it via Western Union (only via bank transfer) / Xoom/ Remitly or any other remittance.


Bank Details:

Name: Naveen Khunteta

Bank Account Number:  1015794367401

IBAN Number:  AE520260001015794367401

City/Country: Dubai, UAE

Swift Code: EBILAEAD

Address: Naveen automation labs FZCO, Scaltiy, building 9W, DAFZA, Dubai, UAE - 000001
3.  Paypal:
Total payment: 265 USD
Use this PayPal id: https://paypal.me/naveenautomation
Check out with PayPal
Note: If you are paying through PayPal, You need to pay 265 USD (10 USD will be the PayPal Fee).
 
 

Syllabus Course Content:

Course Content:

 Testing of WebServices/API:

  1. Introduction of API and WebServices:
    1. What is API
    2. What is WebService
    3. What is Backend Architecture
    4. Rest vs SOAP APIs
    5. What is CRUD operation with different examples
    6. What are different HTTP Calls – GET/POST/PUT/Delete/PATCH/HEAD/OPTIONS
    7. Different Live Projects Examples
  2. Postman:
    1. Introduction
    2. How to call Rest API in Postman
    3. How to pass path parameter in Request
    4. How to pass query parameter in Request
    5. How to set Headers in Postman
    6. How to pass JSON/XML Payload
    7. How to check response status code
    8. How to check JSON/XML response messages
    9. What is response header
    10. Cookies manipulation
    11. Header Presets
    12. API History in Postman
    13. Postman Environment Variables
    14. Postman Test Scripts using Javascript and  Chai Assertions
    15. Run Automated Test Cases in Postman and generate the results
  3. Advance Postman/Newman:
    1. Introduction of Newman
    2. Newman installation/setup
    3. How to run collections from Newman
    4. Newman command line options
    5. Generate HTML Test Report
    6. Create a collection and folders
    7. Create a collection from API Specification or API Schema
    8. maintenance of API collections
    9. Postman Console and logs
    10. Test Script in postman
    11. Pre Request Script in postman
    12. Test Code snippet in postman
    13. Monitoring of APIs
    14. API Documentation
    15. API Documentation/CODES in different programming languages
    16. Publish Documentation
    17. Setup Environment – Local and Global
    18. Collection Runner
    19. Collection Test Summary
    20. Creating a Mock Server for APIs
    21. How to create a team workspace
    22. How to create individual workspace
    23. Import in Postman
    24. Basic and Advanced Settings in Rest Client
    25. Running postman collection with Docker
    26. Running postman collection with Jenkins
  4. How to check APIs at the network layer using developer tools of browser:
    1. How to check Backend services – APIs running behind
    2. What is developer tool in Chrome
    3. How to check request/response of any API in Firefox/Chrome browsers
  5. What are different HTTP Status Response Codes:
    1. 1xx series
    2. 2xx series
    3. 3xx series
    4. 4xx series
    5. 5xx series

Automation Testing of Back End/APIs:

  1. Learn various HTTP Client libraries :
    1. Tools/Library: JDK 11 – HTTP Client
    2. All CRUD – GET/POST/PUT/Delete Calls
    3. How to send Request with Payloads
    4. How to send Query Parameters and Path Parameters
  1. Learn Rest Assured DSL Java Client API:
    1. Introduction of Rest Assured
    2. Rest Assured methods: GET/POST/PUT/Delete/Patch
    3. Handle different payloads using POJO and JSON/XMLs:
    4. Request with Simple JSON format
    5. Request with Complex JSON format
    6. Handle Authentication using Basic Auth, Preemptive Auth, Digest Auth, Bearer Token, Authorization Token, Client ID, Client Secret, API Key, API Secret, OAuth1 and OAuth2
    1. All core features of Rest Assured Library:
      1. GET/POST/PUT/DELETE – Inbuilt BDD Approaches
        1. What is GIVEN/WHEN/THEN/AND methods
        2. What is LOG and ALL methods
        3. How to ASSERT in Rest Assured
        4. How to verify Status Code, Response Body and Headers
        5. How to use QUERY PARAMETERS and PATH PARAMETERS
        6. What is ResponseBuilderSpec and RequestSpecification Concept
        7. What is JSON PATH/XML Path
        8. What is EXTRACT method
        9. How to send a POST CALL with JSON String, JSON File and using Java (POJO) Class.
        10. What is Serialization and De-Serialization
        11. How to use HAMCREST – Assertion Library
      2. GET/POST/PUT/DELETE – NON-BDD Approaches
    2. New End to End Framework using Rest Assured using different real time APIs:
      1. How to setup a Maven Project for APIs
      2. Folder Structure
      3. API Test Automation Design and components
      4. Rest Client Libraries
      5. Write API Automated Tests with TestNG
      6. Data Providers with Parameterization
      7. Data Driven Testing with Excel Files – using Apache POI API
      8. Test Runners with testng.xml
      9. Various Constants Files for Errors, Status Codes, Validation, and Success Messages
      10. Create a GIT Repo for Test Automation project:
        • Create a New Repo
        • Clone a Repo
        • GIT PUSH
        • GIT PULL
        • GIT Check OUT
      11. Integration with Jenkins – CI CD Pipeline and Automation Job
      12. Create the docker Image of API Test Automation
      13. Host/Register docker image to Docker HUB
      14. Download the docker image and Run it on any machines
      15. Advanced Reporting : Extent Report/TestNG Report/Allure Report
      16.  Maven: Build Automation Tool: Run your API Automation Framework from Maven
      17. TestNG Framework for API test cases

8. Mocking APIs using Wiremock library:

  1. Define the dummy APIs
  2. Define API Mock Behaviour for GET/POST Calls
  3. Call Mocking APIs 
  4. Integrate it in your Test Automation

9. Real Time API Examples:

  1. GORest APIs with Authentication
  2. ReqRes.in
  3. Booker APIs
  4. Weather APIs
  5. IMDB APIs
  6. Weather/Forecast Real Time APIs
  7. OAuth APIs
  8. GIT HUB APIs
  9. Twitter APIs
  10. API with Swagger

10 . Life Time Free Access on all the Videos/Recordings/Codes/Notes/PDFs/Cheat Sheets.

 
Cheers!
Naveen AutomationLabs
 

HTTP POST Method Using RestAssured

 

                      ~ Image Source:google/.sashido.io/

Introduction

In this article, we are going to learn about the HTTP Post Method in detail and various ways to create a post payload, in addition to that, we will also learn how to validate Post Response using RestAssured.

Writing post Method

Let’s start writing our first positive scenario :

  1. Given Accept the given content in JSON format
  2. with content type as JSON
  3. and Body
  4. when I performed the Post Request
  5. Then status Code should be 200 OK
  6. And The response should have name as given in JSON body

 

Code with Positive test case

  • As depicted in the screenshot, Primarily, to hit the JSON HTTP post request we need to have JSON Body and passing the JSON body as a string in Body function would suffice our need.
  • This means, once we have the body, we can simply pass our endpoint here in the .post function and once it is successful, we need to assert whether we get the expected output or not.
  • Below is the code for same:

Note: Content type can be XML if you are using XML, else it would be JSON

package com.restassured.tests;

import io.restassured.http.*;
import org.apache.http.HttpStatus;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;

/**
 * @Author: Mandeep Kaur
 */
public class PostMethodTest {

    @Test
    public void sampleTest() {

        // Json Body to pass in the request
        String jsonBody = "{" +
                "   \"name\":\"Test Automation\",\n" +
                "   \"gender\":\"Male\",\n" +
                "   \"email\":\"testAutomation3@gmail.com\",\n" +
                "   \"status\":\"Active\"\n" +
                "}";

        given().header("authorization", "Bearer 0431655cfe7ba40a791e0ce32d83ad33363348919c11627f409a3228f205e15f")
                .accept(ContentType.JSON)
                .contentType(ContentType.JSON)
                .and()
                .body(jsonBody)
                .when()
                .post("https://gorest.co.in/public-api/users")   //hit the post end point
                .then().
                assertThat()
                .statusCode(HttpStatus.SC_OK)
                .and()
                .body("data.name", equalTo("Test Automation")); // Match the output actual to expected

    }
}

Another scenario is the negative case:

Would be if we send the same request, then it should return the response code as “422” and message as email has already been taken because to create user every time unique email should be passed:

Code with negative test case when an email is already existing

JSON Object

Now, the other way of creating the payload/ request is through JSON Object:

JSONObject is an unordered collection of key and value pairs, resembling Java’s native Map implementations.

  • Keys are unique Strings that cannot be null
  • Values can be anything from a Boolean, Number, String, JSONArray or even a JSONObject.NULL object
  • A JSONObject can be represented by a String enclosed within curly braces with keys and values separated by a colon, and pairs separated by a comma
  • It has several constructors with which to construct a JSONObject

Instead of sending the hardcode JSON body, we can send customize data along with post request.

For this scenario,  what we need to do is :

Add this maven dependency in your project

Json Dependency

After that manipulate below JSON request to JSON Object:

{
"name":"Test Automation",
"gender":"Male",
"email":"testAutomation6@gmail.com",
"status":"Active"
}

And here’s the below code for the same :

Post Request by JSONObject

package com.restassured.tests;

import org.json.JSONObject;
import org.junit.Test;
import io.restassured.http.ContentType;
import static io.restassured.RestAssured.given;

/**
 * 
 * @author Mandeep kaur
 *
 */

public class SamplePostRestTest {

	@Test
	public void createUser_whenSuccess() {


		JSONObject jsonObject = new JSONObject();

		//insert key value pair to jsonObject
		jsonObject.put("name", "Test Automation");
		jsonObject.put("gender", "Male");
		jsonObject.put("email", "testAutomation14@gmail.com");
		jsonObject.put("status", "Active");

		String resp=  given().log().all().header("authorization", "Bearer 0431655cfe7ba40a791e0ce32d83ad33363348919c11627f409a3228f205e15f23")
				.accept(ContentType.JSON)
				.contentType("application/json")
				.and()
				.body(jsonObject.toString())
				.post("https://gorest.co.in/public-api/users")   //hit the post end point
				.thenReturn().asString();

		System.out.println(resp);

	}
}

As can be seen, We can use JSONObject and insert the values in the attribute just like hashMap in java and later on, can pass the JSON object in String. After that, validations can be performed accordingly:

And From hashMap also we can create JSON Object like below:

Map<String, String> map = new HashMap<>();
map.put("name", "Test Automation");
map.put("gender", "Male");
map.put("email", "testAutomation14@gmail.com");
map.put("status", "Active");
JSONObject jo = new JSONObject(map);

and this jo object reference can simply be passed in the request.

Since this nature of post request is quite simple, so for the complex request, you need to modify the request as per given specification.

Let’s take a small example:

[
    "Employee",
    {
        "city": "chicago",
        "name": "john",
        "age": "36"
    }
]

Now here it is having array and then a JSON object :

To build this request we need to have this below structure:

JSONArray jsonArray = new JSONArray();
jsonArray.put("Employee");

JSONObject jo = new JSONObject();
jo.put("name", "john");
jo.put("age", "22");
jo.put("city", "chicago");

jsonArray.put(jo);

To illustrate the example above, we first need to create the JSON object and insert values in it, once done then we need to pass this object in JSON Array which again comes from org.json package(below-detailed description of JSONArray), JSON array has its own element as “Employee” which can also be inserted using put() method and finally we can insert this JSONArray into request body like below

JSONArray is an ordered collection of values, resembling Java’s native Vector implementation.

  • Values can be anything from a Number, String, Boolean, JSONArray, JSONObject or even a JSONObject.NULL object
  • It’s represented by a String wrapped within Square Brackets and consists of a collection of values separated by commas
  • Like JSONObject, it has a constructor that accepts a source string and parses it to construct a JSONArray

package com.restassured.tests;

import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import io.restassured.http.ContentType;
import static io.restassured.RestAssured.given;

/**
 * 
 * @author Mandeep kaur
 *
 */

public class SamplePostRestTest {

	@Test
	public void createUser_whenSuccess() {


		JSONArray jsonArray = new JSONArray();
		jsonArray.put("Employee");

		JSONObject jo = new JSONObject();
		jo.put("name", "john");
		jo.put("age", "22");
		jo.put("city", "chicago");

		jsonArray.put(jo);

		 given().log().all().header("authorization", "Bearer 0431655cfe7ba40a791e0ce32d83ad33363348919c11627f409a3228f205e15f23")
				.accept(ContentType.JSON)
				.contentType("application/json")
				.and()
				.body(jsonArray.toString())
				.post("https://gorest.co.in/public-api/users")   //hit the post end point
				.thenReturn().asString();

             }
	}

If there will be any issues with JSON Object, We will get below exception:

 

JSON Exception

The JSONException is the standard exception thrown by this package whenever any error is encountered. This is used across all classes from this package. The exception is usually followed by a message that states what exactly went wrong.

Object Mapping:

Lastly, the other method where payloads can be really complexed, we can go for Object Mapping:

We need to follow below steps :

  • Create a Mapping class also called POJO class (Plain Old Java Objects) and this process is called serialization as we are going to convert the object to the body.
  • Create an object of Mapping class
  • Initialise the values available in the mapping class
  • Send the object along with post request

Let’s analyse the below code

{
“name”:”Test Automation”,
“gender”:”Male”,
“email”:”testAutomation6@gmail.com”,
“status”:”Active”
}

To Create the mapping class, I would say go to  JSONToJavaObject, paste the JSON request and get the Mapping class. As done below:

JsonToPOJO

Mapping class

And our createUser Mapping class will look like this:

package com.restassured.vo;

public class createUserDO  {

    private String name;
    private String gender;
    private String email;
    private String status;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

  
}

Now, the second step is to create an object of Mapping class:

  • createUserDO cu = new createUserDO();
  • Initialised the values via setters i.e setName(“Test Automation”) available in the mapping class.
  • and finally, we sent the object in the post call

package com.restassured.tests;


import org.junit.Test;

import com.restassured.vo.createUserDO;

import io.restassured.http.ContentType;
import static io.restassured.RestAssured.given;

/**
 * 
 * @author Mandeep kaur
 *
 */

public class SamplePostRestTest {

	@Test
	public void createUser_whenSuccess() {
	createUserDO cu = new createUserDO();
        cu.setName("Test Automation");
        cu.setGender("Female");
        cu.setEmail("testAutomation25@gmail.com");
        cu.setStatus("Active");
        
		String resp =  given().log().all().header("authorization", "Bearer 0431655cfe7ba40a791e0ce32d83ad33363348919c11627f409a3228f205e15f")
				.accept(ContentType.JSON)
				.contentType("application/json")
				.and()
				.body(cu)
				.post("https://gorest.co.in/public-api/users")   //hit the post end point
				.thenReturn().asString();
		
		System.out.println(resp);

             }
	}

POST Method via Mapping class

Note: if we need to have logs to verify things, we can simply use log().all() and it can display information on a console like below:

Logs on Console

Since we have converted our object to the body, now to validate the response we can use the process called deserialization of response body, which means converting response body to object.

To do that, the first thing is to create a mapping class for response JSON body, you use the same converter as above json2pojo schema and below code how it is to be done:

Deserialization of Response body

package com.restassured.tests;

import static io.restassured.RestAssured.given;

import org.junit.Test;
import org.testng.Assert;

import com.restassured.vo.CreateUserDO;
import com.restassured.vo.ResponseDataObjects;

import io.restassured.http.ContentType;

/**
 * 
 * @author Mandeep kaur
 *
 */

public class SamplePostRestTest {

	@Test
	public void createUser_whenSuccess() {


		CreateUserDO cu = new CreateUserDO();
        cu.setName("Test Automation");
        cu.setGender("Female");
        cu.setEmail("testAutomation1465@gmail.com");
        cu.setStatus("Active");
        
        
      ResponseDataObjects responseDataObjects =  given().log().all().header("authorization", "Bearer 0431655cfe7ba40a791e0ce32d83ad33363348919c11627f409a3228f205e15f")
				.accept(ContentType.JSON)
				.contentType("application/json")
				.and()
				.body(cu)
				.post("https://gorest.co.in/public-api/users")   //hit the post end point
				.thenReturn().as(ResponseDataObjects.class);
		
		      Assert.assertEquals("Test Automation",responseDataObjects.getData().getName());
        
       

             }
	}

Till .post function we were clear what needs to be performed, the next step is thenReturn(), basically, to fetch the response body after that, as (the method )will take the mapping class(ResponseDataObjects ) to deserialize the response and this will return us the object of our mapping class.

And this class can be used to fetch all the information later on, for validations and verification checks.

Our JSON Response

{
    "code": 201,
    "meta": null,
    "data": {
        "id": 1493,
        "name": "Test Automation",
        "email": "testAutomation701@gmail.com",
        "gender": "Male",
        "status": "Active",
        "created_at": "2021-01-07T12:30:58.987+05:30",
        "updated_at": "2021-01-07T12:30:58.987+05:30"
    }
}

And correspondence POJO class:

Note: we need to use @JsonIgnoreProperties(ignoreUnknown=true)as  is applicable at deserialization of JSON to Java object (POJO) only

package com.restassured.vo;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class ResponseDataObjects {

    private Integer code;
    private Object meta;
    private Data data;

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public Object getMeta() {
        return meta;
    }

    public void setMeta(Object meta) {
        this.meta = meta;
    }

    public Data getData() {
        return data;
    }

    public void setData(Data data) {
        this.data = data;
    }
    
}

package com.restassured.vo;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Data {

	
    private Integer id;
    private String name;
    private String email;
    private String gender;
    private String status;
    private String createdAt;
    private String updatedAt;
    
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(String createdAt) {
        this.createdAt = createdAt;
    }

    public String getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(String updatedAt) {
        this.updatedAt = updatedAt;
    }

}

Conclusion:

In this article, we have learnt how to create a payload using various ways such as via string, JSON Object and with object Mapping and how to fetch the response using Deserialization.

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

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