- 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:RequestSpecificationImpl, TestSpecificationImpl
And in RequestSpecificationImpl class we have below methods such as get() :
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:
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
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:
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:
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 :
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
Someone essentially help to make seriously posts I would state. This is the very first time I frequented your website page and thus far? I surprised with the research you made to make this particular publish incredible. Excellent job!