0% found this document useful (0 votes)
7 views130 pages

Rest Assured

The document outlines various software architecture models including 1-tier, 2-tier, and 3-tier architectures, detailing their components and functionalities. It also provides examples of executing APIs using RestAssured in Java, including GET and POST requests, along with sample code and expected outputs. Additionally, it discusses data extraction from API responses and includes links to relevant resources and assignments.

Uploaded by

omchavan2612
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views130 pages

Rest Assured

The document outlines various software architecture models including 1-tier, 2-tier, and 3-tier architectures, detailing their components and functionalities. It also provides examples of executing APIs using RestAssured in Java, including GET and POST requests, along with sample code and expected outputs. Additionally, it discusses data extraction from API responses and includes links to relevant resources and assignments.

Uploaded by

omchavan2612
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 130

Software architecture: In order to develop a software we need to

have a diagram through which we can understand the in and out to


the application and the process that it performs in order to generate
the output.
1. 1 Tier architecture:
In this we have a single ended platform which comprises of the input
and output specific components to process, generate and store the
output into a single unit.

2. 2 tier architecture:
In this we have a dedicated connection between the output (Client)
and the server in which the client will accept the input and displays
the output keeping the processor at a specific place.
3. 3 tier architecture: In this we have 3 different layers called as
Presentation layer which handles the input provided by the user and
displays the output which it receives from the application layer.
In Application we have all the business logic through which we can
validate the data from the presentation layer and validate the same
to send it ahead for data layer. Data layer is the place where we
manage and store the data into the data base
Components of request:
To download the postman: https://www.postman.com/downloads/

Executing the API using RestAssured:


1. Create the maven project
2. Add the dependencies:
<dependencies>
<!-- https://mvnrepository.com/artifact/io.rest-
assured/rest-assured -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.5.0</version>
<scope>test</scope>
</dependency>
<!--
https://mvnrepository.com/artifact/org.testng/testng
-->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.7.1</version>
<scope>test</scope>
</dependency>
<!--
https://mvnrepository.com/artifact/com.googlecode.jso
n-simple/json-simple -->
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>

</dependencies>

3. Create the package and class followed by execution


of this code:

@Test
public void getListOfUsers()
{
// define the baseURI
RestAssured.baseURI = "https://reqres.in";
// defining the pre requisite in order to
send the data from request

RequestSpecification reqSpecification =
RestAssured.given();
// defining the action to send the request
with request type

RequestSpecification req =
reqSpecification.when();

// Sending the request

Response response = req.get("api/users?


page=2");

String strResponse =
response.asPrettyString();

System.out.println(strResponse);

Output:
SLF4J: See
http://www.slf4j.org/codes.html#StaticLoggerBinder
for further details.
{
"page": 2,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 7,
"email": "[email protected]",
"first_name": "Michael",
"last_name": "Lawson",
"avatar": "https://reqres.in/img/faces/7-
image.jpg"
},
{
"id": 8,
"email": "[email protected]",
"first_name": "Lindsay",
"last_name": "Ferguson",
"avatar": "https://reqres.in/img/faces/8-
image.jpg"
},
{
"id": 9,
"email": "[email protected]",
"first_name": "Tobias",
"last_name": "Funke",
"avatar": "https://reqres.in/img/faces/9-
image.jpg"
},
{
"id": 10,
"email": "[email protected]",
"first_name": "Byron",
"last_name": "Fields",
"avatar":
"https://reqres.in/img/faces/10-image.jpg"
},
{
"id": 11,
"email": "[email protected]",
"first_name": "George",
"last_name": "Edwards",
"avatar":
"https://reqres.in/img/faces/11-image.jpg"
},
{
"id": 12,
"email": "[email protected]",
"first_name": "Rachel",
"last_name": "Howell",
"avatar":
"https://reqres.in/img/faces/12-image.jpg"
}
],
"support": {
"url": "https://contentcaddy.io?
utm_source=reqres&utm_medium=json&utm_campaign=referr
al",
"text": "Tired of writing endless social
media content? Let Content Caddy generate it for
you."
}
}

Optimized solution of the above code:


@Test
public void getListOfUsers() {
// define the baseURI
RestAssured.baseURI = "https://reqres.in";
// defining the pre requisite in order to
send the data from request

Response resp = RestAssured.given()

// defining the action to send the


request with request type

.when()

// Sending the request

.get("api/users?page=2");

String strResponse = resp.asPrettyString();

System.out.println(strResponse);

Output:

{
"page": 2,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 7,
"email": "[email protected]",
"first_name": "Michael",
"last_name": "Lawson",
"avatar": "https://reqres.in/img/faces/7-
image.jpg"
},
{
"id": 8,
"email": "[email protected]",
"first_name": "Lindsay",
"last_name": "Ferguson",
"avatar": "https://reqres.in/img/faces/8-
image.jpg"
},
{
"id": 9,
"email": "[email protected]",
"first_name": "Tobias",
"last_name": "Funke",
"avatar": "https://reqres.in/img/faces/9-
image.jpg"
},
{
"id": 10,
"email": "[email protected]",
"first_name": "Byron",
"last_name": "Fields",
"avatar":
"https://reqres.in/img/faces/10-image.jpg"
},
{
"id": 11,
"email": "[email protected]",
"first_name": "George",
"last_name": "Edwards",
"avatar":
"https://reqres.in/img/faces/11-image.jpg"
},
{
"id": 12,
"email": "[email protected]",
"first_name": "Rachel",
"last_name": "Howell",
"avatar":
"https://reqres.in/img/faces/12-image.jpg"
}
],
"support": {
"url": "https://contentcaddy.io?
utm_source=reqres&utm_medium=json&utm_campaign=referr
al",
"text": "Tired of writing endless social
media content? Let Content Caddy generate it for
you."
}
}

Simplest Approach:

import static io.restassured.RestAssured.*;

import org.testng.annotations.Test;

import io.restassured.response.Response;
public class SimplestApproach {

@Test
public void getListOfUsers()
{
baseURI = "https://reqres.in";
Response resp =
given() .when() .get("api/users?page=2");

String strResponse = resp.asPrettyString();

System.out.println(strResponse);
}

Output:
{
"page": 2,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 7,
"email": "[email protected]",
"first_name": "Michael",
"last_name": "Lawson",
"avatar": "https://reqres.in/img/faces/7-
image.jpg"
},
{
"id": 8,
"email": "[email protected]",
"first_name": "Lindsay",
"last_name": "Ferguson",
"avatar": "https://reqres.in/img/faces/8-
image.jpg"
},
{
"id": 9,
"email": "[email protected]",
"first_name": "Tobias",
"last_name": "Funke",
"avatar": "https://reqres.in/img/faces/9-
image.jpg"
},
{
"id": 10,
"email": "[email protected]",
"first_name": "Byron",
"last_name": "Fields",
"avatar":
"https://reqres.in/img/faces/10-image.jpg"
},
{
"id": 11,
"email": "[email protected]",
"first_name": "George",
"last_name": "Edwards",
"avatar":
"https://reqres.in/img/faces/11-image.jpg"
},
{
"id": 12,
"email": "[email protected]",
"first_name": "Rachel",
"last_name": "Howell",
"avatar":
"https://reqres.in/img/faces/12-image.jpg"
}
],
"support": {
"url": "https://contentcaddy.io?
utm_source=reqres&utm_medium=json&utm_campaign=referr
al",
"text": "Tired of writing endless social
media content? Let Content Caddy generate it for
you."
}
}
Code structure:

Example using the structure:


@Test
public void getSingleUserDetail()
{
baseURI = "https://reqres.in";

Response resp = given()

.when()

.get("api/users/2")

.then()
.extract()// to extract the properties of
response

.response();

String strResp = resp.asPrettyString();

System.out.println(strResp);

int stsCode = resp.statusCode();

System.out.println("Status code is "+stsCode);

Output:
{
"data": {
"id": 2,
"email": "[email protected]",
"first_name": "Janet",
"last_name": "Weaver",
"avatar": "https://reqres.in/img/faces/2-
image.jpg"
},
"support": {
"url": "https://contentcaddy.io?
utm_source=reqres&utm_medium=json&utm_campaign=referr
al",
"text": "Tired of writing endless social
media content? Let Content Caddy generate it for
you."
}
}
Status code is 200
Example for POST :
@Test
public void creatingUser()
{
baseURI = "https://reqres.in";

Response resp = given()

.header("Content-Type", "application/json")

.body("{\r\n"
+
" \"name\": \"att23novRestassured\",\r\n"
+ " \"job\": \"learner\"\r\n"
+ "}")

.when()

.post("/api/users")

.then()

.extract()

.response();

String strResp = resp.asPrettyString();

System.out.println(strResp);

int stsCode = resp.statusCode();

System.out.println(stsCode);

Output:
SLF4J: See
http://www.slf4j.org/codes.html#StaticLoggerBinder
for further details.
{
"name": "att23novRestassured",
"job": "learner",
"id": "31",
"createdAt": "2024-12-26T15:06:59.210Z"
}
201

Link for swagger document:


https://petstore.swagger.io/#/user/createUser

Example for create user api:

@Test
public void creatingUser()
{
baseURI = "https://petstore.swagger.io/v2";

Response resp = given()

.header("Content-Type", "application/json")

.body("{\r\n"
+ " \"id\": 0,\r\n"
+
" \"username\": \"restassureduser\",\r\n"
+ " \"firstName\": \"Tom\",\r\n"
+ " \"lastName\": \"aveston\",\r\n"
+
" \"email\": \"[email protected]\",\r\n"
+ " \"password\": \"Test@1234\",\r\
n"
+ " \"phone\": \"9876543212\",\r\n"
+ " \"userStatus\": 0\r\n"
+ "}")
.when()

.post("/user")

.then()

.extract()

.response();

String strResp = resp.asPrettyString();

System.out.println(strResp);

int stsCode = resp.statusCode();

System.out.println(stsCode);

Output:
{
"code": 200,
"type": "unknown",
"message": "9223372036854760484"
}
200

Assignment:
https://petstore.swagger.io/#/user/getUserByName

WAP to print the response created by GET API using


restassured
Solution:

@Test
public void getUserDetails() {

baseURI = "https://petstore.swagger.io/v2";

Response resp = given()

.when()

.get("/user/Eveningtestuser")

.then()

.extract()

.response();

String responseData = resp.asPrettyString();

System.out.println(responseData);
}

Output:
{
"id": 9223372036854758843,
"username": "Eveningtestuser",
"firstName": "Alex",
"lastName": "smith",
"email": "[email protected]",
"password": "Test@1234",
"phone": "9876543211",
"userStatus": 0
}

Data extraction from Response:


Extraction of properties from the response:
@Test
public void getUserList() {
baseURI = "https://reqres.in";

Response resp = given()

.when()

.get("api/users?page=2")

.then()

.extract()

.response();

int stsCode = resp.statusCode();// to get the


status code of the response

System.out.println("Value of status code is "


+ stsCode);

String stsLine = resp.statusLine();// to get


the status line of the response that we have received

System.out.println("Status line is " +


stsLine);

long responseTime = resp.getTime();// to get


the response time of the request

System.out.println("Response time is " +


responseTime);

Headers allHeaders = resp.headers(); // this


method is used to fetch all headers from response
System.out.println(allHeaders);

List<Header> listOfHeader =
allHeaders.asList();

int number = listOfHeader.size();

System.out.println(number);

for(Header valueOfHeader :listOfHeader)


{
System.out.println(valueOfHeader);
}

String valueOfHeader =
resp.getHeader("Content-Type");

System.out.println(valueOfHeader);

Output:
Value of status code is 200
Status line is HTTP/1.1 200 OK
Response time is 2342
Date=Fri, 27 Dec 2024 14:53:40 GMT
Content-Type=application/json; charset=utf-8
Transfer-Encoding=chunked
Connection=keep-alive
Report-To={"group":"heroku-
nel","max_age":3600,"endpoints":[{"url":"https://
nel.heroku.com/reports?ts=1735310137&sid=c4c9725f-
1ab0-44d8-820f-
430df2718e11&s=Yg7JOOFgS7kcs3fRcEgaTly18V9uwRrYRVgcs9
xSkXA%3D"}]}
Reporting-Endpoints=heroku-nel=https://
nel.heroku.com/reports?ts=1735310137&sid=c4c9725f-
1ab0-44d8-820f-
430df2718e11&s=Yg7JOOFgS7kcs3fRcEgaTly18V9uwRrYRVgcs9
xSkXA%3D
Nel={"report_to":"heroku-
nel","max_age":3600,"success_fraction":0.005,"failure
_fraction":0.05,"response_headers":["Via"]}
X-Powered-By=Express
Access-Control-Allow-Origin=*
Etag=W/"440-ZjsmMKR8P3usr2uJZbOCGCxC3Uw"
Via=1.1 vegur
Cache-Control=max-age=14400
CF-Cache-Status=HIT
Age=1083
Vary=Accept-Encoding
Server=cloudflare
CF-RAY=8f8a2435bb484910-BOM
Content-Encoding=gzip
server-timing=cfL4;desc="?
proto=TCP&rtt=11231&min_rtt=9585&rtt_var=4770&sent=7&
recv=7&lost=0&retrans=0&sent_bytes=3107&recv_bytes=77
5&delivery_rate=441940&cwnd=246&unsent_bytes=0&cid=64
2019968b39b392&ts=679&x=0"
19
Date=Fri, 27 Dec 2024 14:53:40 GMT
Content-Type=application/json; charset=utf-8
Transfer-Encoding=chunked
Connection=keep-alive
Report-To={"group":"heroku-
nel","max_age":3600,"endpoints":[{"url":"https://
nel.heroku.com/reports?ts=1735310137&sid=c4c9725f-
1ab0-44d8-820f-
430df2718e11&s=Yg7JOOFgS7kcs3fRcEgaTly18V9uwRrYRVgcs9
xSkXA%3D"}]}
Reporting-Endpoints=heroku-nel=https://
nel.heroku.com/reports?ts=1735310137&sid=c4c9725f-
1ab0-44d8-820f-
430df2718e11&s=Yg7JOOFgS7kcs3fRcEgaTly18V9uwRrYRVgcs9
xSkXA%3D
Nel={"report_to":"heroku-
nel","max_age":3600,"success_fraction":0.005,"failure
_fraction":0.05,"response_headers":["Via"]}
X-Powered-By=Express
Access-Control-Allow-Origin=*
Etag=W/"440-ZjsmMKR8P3usr2uJZbOCGCxC3Uw"
Via=1.1 vegur
Cache-Control=max-age=14400
CF-Cache-Status=HIT
Age=1083
Vary=Accept-Encoding
Server=cloudflare
CF-RAY=8f8a2435bb484910-BOM
Content-Encoding=gzip
server-timing=cfL4;desc="?
proto=TCP&rtt=11231&min_rtt=9585&rtt_var=4770&sent=7&
recv=7&lost=0&retrans=0&sent_bytes=3107&recv_bytes=77
5&delivery_rate=441940&cwnd=246&unsent_bytes=0&cid=64
2019968b39b392&ts=679&x=0"
application/json; charset=utf-8

Data extraction from Body: We can extract the data


from response body using multiple ways:
1. using jsonPath() method
2. using class
3. using Serialization and Deserialization

Example:
public class DataExtractionFromBody1 {

@Test
public void creatingUser()
{
baseURI = "https://petstore.swagger.io/v2";

Response resp = given()

.header("Content-Type", "application/json")

.body("{\r\n"
+ " \"id\": 0,\r\n"
+ " \"username\": \"27DecUser\",\r\
n"
+ " \"firstName\": \"Tom\",\r\n"
+ " \"lastName\": \"aveston\",\r\n"
+
" \"email\": \"[email protected]\",\r\n"
+ " \"password\": \"Test@1234\",\r\
n"
+ " \"phone\": \"9876543212\",\r\n"
+ " \"userStatus\": 0\r\n"
+ "}")

.when()

.post("/user")

.then()

.extract()

.response();

String strResp = resp.asPrettyString();

System.out.println(strResp);

JsonPath jp = resp.jsonPath();

String messageValue = jp.getString("message"); //This


will fetch the data and return as String based on the
path - message

System.out.println(messageValue);//
9223372036854759463

int codeValue = jp.getInt("code");// This will fetch


the data and return as Int type based on the path -
code

System.out.println(codeValue);//200

Assert.assertEquals(codeValue, 200);

}
}

Output:
{
"code": 200,
"type": "unknown",
"message": "9223372036854759463"
}
9223372036854759463
200

Assignment:
WAP to create the user using Create user API and then
using get API validate the firstname of the user

Solution:
@Test
public void createUser()
{
baseURI = "https://petstore.swagger.io/v2";

Response resp = given()

.header("Content-Type",
"application/json")

.body("{\r\n"
+ " \"id\": 0,\r\n"
+
" \"username\": \"restassureduser2\",\r\n"
+
" \"firstName\": \"David\",\r\n"
+
" \"lastName\": \"aveston\",\r\n"
+
" \"email\": \"[email protected]\",\r\n"
+
" \"password\": \"Test@1234\",\r\n"
+
" \"phone\": \"9876543212\",\r\n"
+ " \"userStatus\": 0\r\n"
+ "}")

.when()

.post("/user")

.then()

.extract()

.response();

String strResp = resp.asPrettyString();

System.out.println(strResp);

@Test
public void getDetails()
{
baseURI = "https://petstore.swagger.io/v2";

Response resp = given()

.when()

.get("/user/restassureduser2")

.then()

.extract()
.response();

String strResp = resp.asPrettyString();


System.out.println(strResp);

JsonPath jp = resp.jsonPath();

String firstName = jp.getString("firstName");

System.out.println(firstName);

Assert.assertEquals(firstName, "David");

Output:
{
"code": 200,
"type": "unknown",
"message": "9223372036854757527"
}
{
"id": 9223372036854757527,
"username": "restassureduser2",
"firstName": "David",
"lastName": "aveston",
"email": "[email protected]",
"password": "Test@1234",
"phone": "9876543212",
"userStatus": 0
}
David
Example 2:

@Test
public void getUserDetails()
{
RestAssured.baseURI = "https://reqres.in/";

Response resp = given()

.when()

.get("api/users/2")

.then()

.extract()

.response();

String strResp = resp.asPrettyString();

System.out.println(strResp);

JsonPath jp = resp.jsonPath();

String textValue = jp.getString("support.text");

System.out.println(textValue);

Output:
{
"data": {
"id": 2,
"email": "[email protected]",
"first_name": "Janet",
"last_name": "Weaver",
"avatar": "https://reqres.in/img/faces/2-
image.jpg"
},
"support": {
"url": "https://contentcaddy.io?
utm_source=reqres&utm_medium=json&utm_campaign=referr
al",
"text": "Tired of writing endless social
media content? Let Content Caddy generate it for
you."
}
}
Tired of writing endless social media content? Let
Content Caddy generate it for you.

Handling Array available in response:


Example:

@Test
public void getDataFromArray()
{
RestAssured.baseURI = "https://reqres.in/";

Response resp = given()

.when()

.get("api/users?page=2")

.then()

.extract()

.response();

String stringResp = resp.asPrettyString();

System.out.println(stringResp);

JsonPath jp = resp.jsonPath();
String fName =
jp.getString("data[0].first_name");

String zerothIndex = jp.getString("data[0]");

System.out.println(fName);

System.out.println(zerothIndex);
int numberOfElementsPresentInArray =
jp.getInt("data.size()");// to get the size of an
array

System.out.println("Total number of elements are:


"+numberOfElementsPresentInArray);

}
Output:
{
"page": 2,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 7,
"email": "[email protected]",
"first_name": "Michael",
"last_name": "Lawson",
"avatar": "https://reqres.in/img/faces/7-
image.jpg"
},
{
"id": 8,
"email": "[email protected]",
"first_name": "Lindsay",
"last_name": "Ferguson",
"avatar": "https://reqres.in/img/faces/8-
image.jpg"
},
{
"id": 9,
"email": "[email protected]",
"first_name": "Tobias",
"last_name": "Funke",
"avatar": "https://reqres.in/img/faces/9-
image.jpg"
},
{
"id": 10,
"email": "[email protected]",
"first_name": "Byron",
"last_name": "Fields",
"avatar":
"https://reqres.in/img/faces/10-image.jpg"
},
{
"id": 11,
"email": "[email protected]",
"first_name": "George",
"last_name": "Edwards",
"avatar":
"https://reqres.in/img/faces/11-image.jpg"
},
{
"id": 12,
"email": "[email protected]",
"first_name": "Rachel",
"last_name": "Howell",
"avatar":
"https://reqres.in/img/faces/12-image.jpg"
}
],
"support": {
"url": "https://contentcaddy.io?
utm_source=reqres&utm_medium=json&utm_campaign=referr
al",
"text": "Tired of writing endless social
media content? Let Content Caddy generate it for
you."
}
}
Michael
[id:7, email:[email protected],
first_name:Michael, last_name:Lawson,
avatar:https://reqres.in/img/faces/7-image.jpg]
Total number of elements are: 6

Assignment : WAP to fetch the lastname of the user whose first


name is “Rachel”

Fetching the data from ready made json:


@Test
public void getDataFromJson()
{
String json = "{\r\n"
+ "\"dashboard\": {\r\n"
+ "\"purchaseAmount\": 910,\r\n"
+ "\"website\": \"www.abc.com\"\r\n"
+ "},\r\n"
+ "\"courses\": [\r\n"
+ "{\r\n"
+ "\"title\": \"Selenium Python\",\
r\n"
+ "\"price\": 50,\r\n"
+ "\"copies\": 6\r\n"
+ "},\r\n"
+ "{\r\n"
+ "\"title\": \"Cypress\",\r\n"
+ "\"price\": 40,\r\n"
+ "\"copies\": 4\r\n"
+ "},\r\n"
+ "{\r\n"
+ "\"title\": \"RPA\",\r\n"
+ "\"price\": 45,\r\n"
+ "\"copies\": 10\r\n"
+ "}\r\n"
+ "]\r\n"
+ "}\r\n"
+ "";

// to fetch the data from ready made json we


need to use JsonPath class

JsonPath jp = new JsonPath(json);

String websitePath =
jp.getString("dashboard.website");

System.out.println(websitePath);

Output:
www.abc.com

Ready made json:


{
"dashboard": {
"purchaseAmount": 910,
"website": "www.abc.com"
},
"courses": [
{
"title": "Selenium Python",
"price": 50,
"copies": 6
},
{
"title": "Cypress",
"price": 40,
"copies": 4
},
{
"title": "RPA",
"price": 45,
"copies": 10
}
]
}

Assignment:
1. Print No of courses returned by API

2. Print Purchase Amount

3. Print Title of the first course

4. Print all course titles and their respective Prices

5. Print no of copies sold by RPA Course

6. Verify if Sum of all Course prices matches with Purchase Amount

Solution 6:
@Test
public void getDataFromJson()
{
String json = "{\r\n"
+ "\"dashboard\": {\r\n"
+ "\"purchaseAmount\": 910,\r\n"
+ "\"website\": \"www.abc.com\"\r\n"
+ "},\r\n"
+ "\"courses\": [\r\n"
+ "{\r\n"
+ "\"title\": \"Selenium Python\",\
r\n"
+ "\"price\": 50,\r\n"
+ "\"copies\": 6\r\n"
+ "},\r\n"
+ "{\r\n"
+ "\"title\": \"Cypress\",\r\n"
+ "\"price\": 40,\r\n"
+ "\"copies\": 4\r\n"
+ "},\r\n"
+ "{\r\n"
+ "\"title\": \"RPA\",\r\n"
+ "\"price\": 45,\r\n"
+ "\"copies\": 10\r\n"
+ "}\r\n"
+ "]\r\n"
+ "}\r\n"
+ "";

// to fetch the data from ready made json we


need to use JsonPath class

JsonPath jp = new JsonPath(json);

String websitePath =
jp.getString("dashboard.website");

System.out.println(websitePath);

// solution for verify if Sum of all Course


prices matches with Purchase Amount

int numberOfCourse =
jp.getInt("courses.size()");

int sum = 0;
for(int i=0; i<numberOfCourse; i++)
{
int priceValue =
jp.getInt("courses["+i+"].price");

int copiesValue =
jp.getInt("courses["+i+"].copies");

sum = sum + (priceValue * copiesValue);

System.out.println("Sum value is : "+sum);

int purchaseValue =
jp.getInt("dashboard.purchaseAmount");

System.out.println("purchaseValue value is :
"+purchaseValue);

Assert.assertEquals(sum, purchaseValue);

Output:
www.abc.com
Sum value is : 910
purchaseValue value is : 910

Ecommerce project:
Link: https://rahulshettyacademy.com/client/
To create an account we need to click on the register button:

Verify setting in postman if it is enabled or not to upload the file via


API:
1. Click on the settings
2. Again click on settings
3. Check if the toggle button to read the files outside the working
directory is enabled or not
API Chaining: It is a process in which we apply the output data as an
input to the following api and perform the same action way forward
is called as API chaining.

Ecommerce project API:


public class POST_Login extends BaseData {

@Test
public void loginToApp()
{
RestAssured.baseURI =
"https://rahulshettyacademy.com";

Response resp = given()

.body("{\r\n"
+
" \"userEmail\": \"[email protected]\",\r\n"
+
" \"userPassword\": \"Test@1234\"\r\n"
+ "}")
.header("Content-Type", "application/json")

.when()

.post("api/ecom/auth/login")

.then()

.extract()

.response();

String strResp = resp.asPrettyString();

System.out.println(strResp);

// Fetching the value of token and userid from the


response

JsonPath jp = resp.jsonPath();
token = jp.getString("token");

System.out.println(token);

usrId = jp.getString("userId");

System.out.println(usrId);

public class AddProduct extends BaseData{

@Test
public void addProductToApp()
{
String pathOfImage =
System.getProperty("user.dir")+"\\TestImage2.png";

File file = new File(pathOfImage);

RestAssured.baseURI =
"https://rahulshettyacademy.com";

Response resp = given()

.param("productName", "Jeans")

.param("productAddedBy", usrId)

.param("productCategory", "fashion")

.param("productSubCategory", "Trouser")

.param("productPrice", "1500")

.param("productDescription", "Casual Jeans


for Women")

.param("productFor", "Women")
.multiPart("productImage", file)

.header("Authorization", token)

.when()

.post("api/ecom/product/add-product")

.then()

.extract()

.response();

String strResp = resp.asPrettyString();

System.out.println(strResp);

JsonPath jp = resp.jsonPath();

productIdValue = jp.getString("productId");

}
public class PlaceOrder extends BaseData {

@Test
public void placingOrder()
{
RestAssured.baseURI =
"https://rahulshettyacademy.com";

// RestAssured.useRelaxedHTTPSValidation();

Response resp = given()

.header("Content-Type", "application/json")

.header("Authorization", token)

.body("{\r\n"
+ " \"orders\": [\r\n"
+ " {\r\n"
+ " \"country\": \"India\", \
r\n"
+
" \"productOrderedId\" : \""+productIdValue+"\
"\r\n"
+ " }\r\n"
+ " ]\r\n"
+ "}")

.when()

.post("/api/ecom/order/create-order")

.then()

.extract()

.response();

String responseValue = resp.asPrettyString();

System.out.println(responseValue);
}

public class DeleteProduct extends BaseData {

@Test
public void deletingProduct()
{
RestAssured.baseURI =
"https://rahulshettyacademy.com";

Response resp = given()

.header("Authorization", token)

.when()

.delete("/api/ecom/product/delete-
product/"+productIdValue)
.then()

.extract()

.response();

String respValue = resp.asPrettyString();

System.out.println(respValue);

}
public class BaseData {

static String token;


static String usrId;
static String productIdValue;

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE suite SYSTEM "https://testng.org/testng-
1.0.dtd">
<suite name="Suite">
<test thread-count="5" name="Test">
<classes>
<class name="ecom.POST_Login"/>
<class name="ecom.AddProduct"/>
<class name="ecom.PlaceOrder"/>
<class name="ecom.DeleteProduct"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->

Output post running the xml file:


{
"token":
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2Nzc
1NGZiYWUyYjU0NDNiMWYwZDM0YzMiLCJ1c2VyRW1haWwiOiJhdHQy
M25vdkBnbWFpbC5jb20iLCJ1c2VyTW9iaWxlIjo4ODc3NjY1NTQ0L
CJ1c2VyUm9sZSI6ImN1c3RvbWVyIiwiaWF0IjoxNzM1ODMwMjUwLC
JleHAiOjE3NjczODc4NTB9.5aMSSjxFha3FSJ_q6KnaxJuZXCcrJv
cOI8N3_Ea1CCI",
"userId": "67754fbae2b5443b1f0d34c3",
"message": "Login Successfully"
}
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2Nzc1
NGZiYWUyYjU0NDNiMWYwZDM0YzMiLCJ1c2VyRW1haWwiOiJhdHQyM
25vdkBnbWFpbC5jb20iLCJ1c2VyTW9iaWxlIjo4ODc3NjY1NTQ0LC
J1c2VyUm9sZSI6ImN1c3RvbWVyIiwiaWF0IjoxNzM1ODMwMjUwLCJ
leHAiOjE3NjczODc4NTB9.5aMSSjxFha3FSJ_q6KnaxJuZXCcrJvc
OI8N3_Ea1CCI
67754fbae2b5443b1f0d34c3
{
"productId": "6776aaefe2b5443b1f0ef1da",
"message": "Product Added Successfully"
}
{
"orders": [
"6776aaefe2b5443b1f0ef1de"
],
"productOrderId": [
"6776aaefe2b5443b1f0ef1da"
],
"message": "Order Placed Successfully"
}
{
"message": "Product Deleted Successfully"
}

Sending body as a Java Object:


public void createUser_WithJavaObject()
{
LinkedHashMap<String,Object> hm = new
LinkedHashMap<String, Object>();

hm.put("id", 0);
hm.put("username", "javaobjectuser");
hm.put("firstName", "Daniel");
hm.put("lastName", "henry");
hm.put("email", "[email protected]");
hm.put("password", "Test@1234");
hm.put("phone", "9988778655");
hm.put("userStatus", 0);

RestAssured.baseURI =
"https://petstore.swagger.io/v2";

Response resp = given()

.header("Content-Type", "application/json")

.body(hm)

.log().all()

.when()

.post("/user")

.then()

.log().all()

.extract()

.response();

String strResp = resp.asPrettyString();

System.out.println(strResp);

}
Output:
Request method: POST
Request URI: https://petstore.swagger.io/v2/user
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: Accept=*/*
Content-Type=application/json
Cookies: <none>
Multiparts: <none>
Body:
{
"id": 0,
"username": "javaobjectuser",
"firstName": "Daniel",
"lastName": "henry",
"email": "[email protected]",
"password": "Test@1234",
"phone": "9988778655",
"userStatus": 0
}
HTTP/1.1 200 OK
Date: Fri, 03 Jan 2025 14:22:36 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, DELETE, PUT
Access-Control-Allow-Headers: Content-Type, api_key,
Authorization
Server: Jetty(9.2.9.v20150224)

{
"code": 200,
"type": "unknown",
"message": "9223372036854775807"
}
{
"code": 200,
"type": "unknown",
"message": "9223372036854775807"
}

Note: log().all() method is used to log all the


details that we are sending as well as receiving as a
part of request and response.

Creating the Mock server:


1. Click on mock server

2. Click on ‘+’ button to create the mock server

3. Select the existing collection and click on Next button


4. Enter the mock server name and click on create mock server
https://82ac28ee-c468-42d4-b652-5ac5aed990f8.mock.pstmn.io

Creating a dummy API


Define any arbitrary end point along with the base uri and send the
request followed by click on save response

First request curl (Only copy the highlighted content and paste it in
the postman:

curl --location 'https://82ac28ee-c468-42d4-b652-


5ac5aed990f8.mock.pstmn.io/att23eveningpostcall' \
--header 'x-mock-match-request-body: true' \
--header 'Content-Type: application/json' \
--data '[
{"id" : "1000", "type" : "grains"},
{"id" : "1001" , "type" : "beverage"}
]
'
Example to send the data as a java object:
@Test
public void sendingRequestToMockServer()
{
HashMap<String, String> zerothElement =
new HashMap<String, String>();

zerothElement.put("id", "1000");
zerothElement.put("type", "grains");

HashMap<String, String> firstElement =


new HashMap<String, String>();

firstElement.put("id", "1001");
firstElement.put("type", "beverage");

List<HashMap<String, String>> mainObject


= new ArrayList<HashMap<String,String>>();

mainObject.add(zerothElement);

mainObject.add(firstElement);

RestAssured.baseURI = "https://82ac28ee-c468-
42d4-b652-5ac5aed990f8.mock.pstmn.io";

given()

.header("Content-Type", "application/json")

.header("x-mock-match-request-body", "true")

.body(mainObject)

.log().all()

.when()

.post("att23eveningpostcall")

.then()

.log().all()
.extract()

.response();

Output:
Request method: POST
Request URI: https://82ac28ee-c468-42d4-b652-
5ac5aed990f8.mock.pstmn.io/att23eveningpostcall
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: x-mock-match-request-body=true
Accept=*/*
Content-Type=application/json
Cookies: <none>
Multiparts: <none>
Body:
[
{
"id": "1000",
"type": "grains"
},
{
"id": "1001",
"type": "beverage"
}
]
HTTP/1.1 200 OK
Date: Fri, 03 Jan 2025 15:11:29 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 60
Connection: keep-alive
x-srv-trace: v=1;t=42e90dd62bc845c2
x-srv-span: v=1;s=b7a2ba339a2d41f7
Access-Control-Allow-Origin: *
X-RateLimit-Limit: 120
X-RateLimit-Remaining: 119
X-RateLimit-Reset: 1735915515
ETag: W/"a4-7hO0T/XLq3TuFViTu2ZVQQdIY+A"
Vary: Accept-Encoding

{
"Message": "Request body matched with the
example"
}

Assignment:
WAP to create the java object for this json:

{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": [
5, 9
], "type": "Chocolate" }

]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" }

]}

Curl for the above json:


curl --location 'https://82ac28ee-c468-42d4-b652-
5ac5aed990f8.mock.pstmn.io/att23novcomplexjson' \
--header 'x-mock-match-request-body: true' \
--header 'Content-Type: application/json' \
--data '{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters": {
"batter": [
{
"id": "1001",
"type": "Regular"
},
{
"id": [
5,
9
],
"type": "Chocolate"
}
]
},
"topping": [
{
"id": "5001",
"type": "None"
},
{
"id": "5002",
"type": "Glazed"
},
{
"id": "5005",
"type": "Sugar"
}
]
}'

Solution for complex json:


@Test
public void sendingComplexJson() {
// array of id element

List<Integer> arrayOfId = new


ArrayList<Integer>();
arrayOfId.add(5);
arrayOfId.add(9);

// index elements of an array

HashMap<String, Object> batterHashMap1 = new


HashMap<String, Object>();

batterHashMap1.put("id", "1001");
batterHashMap1.put("type", "Regular");

HashMap<String, Object> batterHashMap2 = new


HashMap<String, Object>();

batterHashMap2.put("id", arrayOfId);
batterHashMap2.put("type", "Chocolate");

// batter's value array

List<HashMap<String, Object>> batterArray =


new ArrayList<HashMap<String, Object>>();

batterArray.add(batterHashMap1);
batterArray.add(batterHashMap2);

// batters json
HashMap<String, List<HashMap<String,
Object>>> batterHashMap = new HashMap<String,
List<HashMap<String, Object>>>();
batterHashMap.put("batter", batterArray);

// topping array

HashMap<String, String> zerothIndex = new


HashMap<String, String>();

zerothIndex.put("id", "5001");
zerothIndex.put("type", "None");

HashMap<String, String> firstIndex = new


HashMap<String, String>();

firstIndex.put("id", "5002");
firstIndex.put("type", "Glazed");

HashMap<String, String> secondIndex = new


HashMap<String, String>();

secondIndex.put("id", "5005");
secondIndex.put("type", "Sugar");

List<HashMap<String, String>> toppingArray =


new ArrayList<HashMap<String, String>>();
toppingArray.add(zerothIndex);
toppingArray.add(firstIndex);
toppingArray.add(secondIndex);

HashMap<String, Object> mainObject = new


HashMap<String, Object>();

mainObject.put("id", "0001");
mainObject.put("type", "donut");
mainObject.put("name", "Cake");
mainObject.put("ppu", 0.55);
mainObject.put("batters", batterHashMap);
mainObject.put("topping", toppingArray);
RestAssured.baseURI = "https://82ac28ee-c468-
42d4-b652-5ac5aed990f8.mock.pstmn.io";

given()

.header("x-mock-match-request-body", "true")

.header("Content-Type", "application/json")

.log().all()

.body(mainObject)

.when()

.post("att23novcomplexjson")

.then()

.log().all()

.extract()

.response();

Output:
Request method: POST
Request URI: https://82ac28ee-c468-42d4-b652-
5ac5aed990f8.mock.pstmn.io/att23novcomplexjson
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: x-mock-match-request-body=true
Accept=*/*
Content-Type=application/json
Cookies: <none>
Multiparts: <none>
Body:
{
"ppu": 0.55,
"batters": {
"batter": [
{
"id": "1001",
"type": "Regular"
},
{
"id": [
5,
9
],
"type": "Chocolate"
}
]
},
"name": "Cake",
"id": "0001",
"type": "donut",
"topping": [
{
"id": "5001",
"type": "None"
},
{
"id": "5002",
"type": "Glazed"
},
{
"id": "5005",
"type": "Sugar"
}
]
}
HTTP/1.1 201 Created
Date: Tue, 07 Jan 2025 14:46:10 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 60
Connection: keep-alive
x-srv-trace: v=1;t=d30481c4e4d1e295
x-srv-span: v=1;s=406be2cfe30508d1
Access-Control-Allow-Origin: *
X-RateLimit-Limit: 120
X-RateLimit-Remaining: 119
X-RateLimit-Reset: 1735917814
ETag: W/"96-S/5iQ2y1qqIInh5BwoPc+chvDJU"
Vary: Accept-Encoding

{
"Message": "Request body matched with the
example"
}

Serialization and De-serialization:

Serialization: It is a process to convert a java object into byte stream


Deserialization: It is a process to convert the byte stream into java
object.

Advantage of Serialization and deserialization:


1. Readability of the code gets improve
2. Ease of sending complex object in request.
3. Ability to configure the data inside the method of pojo class to
avoid hard coding.
4. Improves the reusability and maintainability.

Example:
Pojo class: Pojo class is an abbreviation of plain old java object which
contains the getter and setter methods along with the variables
which are private and called inside the methods.
It is used to define the structure of the json.

Request body pojo class:


public class CreateUserRequestBody {

private Integer id;


private String username;
private String firstName;
private String lastName;
private String email;
private String password;
private String phone;
private Integer userStatus;

//ALT + SHIFT + S - getter and setter shortcut

public Integer getId() {


return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Integer getUserStatus() {
return userStatus;
}
public void setUserStatus(Integer userStatus) {
this.userStatus = userStatus;
}

Response body pojo class:


public class CreateUserResponseBody {

private Integer code;


private String type;
private String message;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

Request:
@Test
public void createUser()
{
CreateUserRequestBody mainObj = new
CreateUserRequestBody();

mainObj.setId(0);
mainObj.setUsername("serialized_user2");
mainObj.setFirstName("Daniel");
mainObj.setLastName("Lawson");
mainObj.setEmail("[email protected]");
mainObj.setPassword("Test@1234");
mainObj.setPhone("9876543610");
mainObj.setUserStatus(0);

RestAssured.baseURI =
"https://petstore.swagger.io/v2";

Response resp = given()

.header("Content-Type", "application/json")

.body(mainObj)

.log().all()

.when()

.post("user")

.then()

.log().all()

.extract()

.response();
CreateUserResponseBody responseObject =
resp.as(CreateUserResponseBody.class);

Integer codeValue = responseObject.getCode();

System.out.println("Code value is :"+codeValue);

String messageValue =
responseObject.getMessage();

System.out.println("Message value is
"+messageValue);

Output:
Request method: POST
Request URI: https://petstore.swagger.io/v2/user
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: Accept=*/*
Content-Type=application/json
Cookies: <none>
Multiparts: <none>
Body:
{
"id": 0,
"username": "serialized_user2",
"firstName": "Daniel",
"lastName": "Lawson",
"email": "[email protected]",
"password": "Test@1234",
"phone": "9876543610",
"userStatus": 0
}
HTTP/1.1 200 OK
Date: Wed, 08 Jan 2025 14:51:31 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, DELETE, PUT
Access-Control-Allow-Headers: Content-Type, api_key,
Authorization
Server: Jetty(9.2.9.v20150224)

{
"code": 200,
"type": "unknown",
"message": "9223372036854771941"
}
Code value is :200
Message value is 9223372036854771941

Example 2:
Pojo class for get list of users:

public class GetListOfUsersResponseBody {

private Integer page;


private Integer per_page;
private Integer total;
private Integer total_pages;
private List<Data> data;
private Support support;

public Integer getPage() {


return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getPer_page() {
return per_page;
}
public void setPer_page(Integer per_page) {
this.per_page = per_page;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public Integer getTotal_pages() {
return total_pages;
}
public void setTotal_pages(Integer total_pages) {
this.total_pages = total_pages;
}
public List<Data> getData() {
return data;
}
public void setData(List<Data> data) {
this.data = data;
}
public Support getSupport() {
return support;
}
public void setSupport(Support support) {
this.support = support;
}

public class Data {

private Integer id;


private String email;
private String first_name;
private String last_name;
private String avatar;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}

}
public class Support {

private String url;


private String text;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}

}
@Test
public void getListOfUsers()
{
RestAssured.baseURI = "https://reqres.in/";

Response resp = given()

.when()

.get("api/users?page=2")

.then()

.extract()

.response();

GetListOfUsersResponseBody responseObject =
resp.as(GetListOfUsersResponseBody.class);

Integer totalValue =
responseObject.getTotal();

System.out.println("Total value from response


body is : "+totalValue);

}
Output:
Total value from response body is : 12

Assignment: WAP to fetch the lastname of Ist index


position using deserialization

Solution:
public void getListOfUsers()
{
RestAssured.baseURI =
"https://reqres.in/";

Response resp = given()

.when()

.get("api/users?page=2")

.then()

.extract()

.response();

GetListOfUsersResponseBody
responseObject =
resp.as(GetListOfUsersResponseBody.class);

Integer totalValue =
responseObject.getTotal();

System.out.println("Total value from


response body is : "+totalValue);

// fetching the lastname of Ist index


position from Data Array

List<Data> dataObject =
responseObject.getData();
Data firstIndex = dataObject.get(1);

String lastnameOfFirstIndex =
firstIndex.getLast_name();

System.out.println(lastnameOfFirstIndex);

Support supportObject =
responseObject.getSupport();

String urlValue = supportObject.getUrl();

System.out.println(urlValue);

}
Output:
Total value from response body is : 12
Ferguson
https://contentcaddy.io?
utm_source=reqres&utm_medium=json&utm_campaign=referr
al

Assignment :
WAP to send the below json as a java object using
pojo class:
{

"id": "0001",

"type": "donut",

"name": "Cake",

"ppu": 0.55,

"batters": {

"batter": [

{
"id": "1001",

"type": "Regular"

},

"id": [

5,

],

"type": "Chocolate"

},

"topping": [

"id": "5001",

"type": "None"

},

"id": "5002",

"type": "Glazed"

},

"id": "5005",

"type": "Sugar"

Spec Builders: It is a concept in which we can define the common


properties with respect to request using a class RequestSpecBuilder
and form an reference variable called as RequestSpecification and
interms of response properties we create based on
ResponseSpecBuilder class and create a reference variable of
ResponseSpecification type.
Example:
public class RequestAndResponseSpecBuilder {
RequestSpecification requestSpecification;

ResponseSpecification responseSpecification;

@BeforeClass
public void initRequestAndResponseSpecBuilder() {
RequestSpecBuilder requestSpecBuilder = new
RequestSpecBuilder();

requestSpecBuilder.setBaseUri("https://petstore.swagg
er.io");
requestSpecBuilder.setBasePath("/v2");
requestSpecBuilder.addHeader("Content-Type",
"application/json");
requestSpecBuilder.log(LogDetail.ALL);
requestSpecification =
requestSpecBuilder.build();

ResponseSpecBuilder responseSpecBuilder = new


ResponseSpecBuilder();

responseSpecBuilder.expectContentType(ContentType.JSO
N);
responseSpecBuilder.expectStatusCode(200);
responseSpecBuilder.log(LogDetail.ALL);
responseSpecification =
responseSpecBuilder.build();

@Test
public void createUser() {
given().spec(requestSpecification)

.body("{\r\n" + " \"id\": 0,\r\n" +


" \"username\": \"restasssureduser\",\r\n"
+
" \"firstName\": \"Rest\",\r\n" +
" \"lastName\": \"Assured\",\r\n"
+
" \"email\": \"[email protected]\",\r\n" +
" \"password\": \"Test@1234\",\r\n"
+
" \"phone\": \"9876543210\",\r\n" +
" \"userStatus\": 0\r\n" + "}")

.when()

.post("user")

.then()
.spec(responseSpecification)

.extract()

.response();

Output:
Request method: POST
Request URI: https://petstore.swagger.io/v2/user
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: Accept=*/*
Content-Type=application/json
Cookies: <none>
Multiparts: <none>
Body:
{
"id": 0,
"username": "restasssureduser",
"firstName": "Rest",
"lastName": "Assured",
"email": "[email protected]",
"password": "Test@1234",
"phone": "9876543210",
"userStatus": 0
}
HTTP/1.1 200 OK
Date: Thu, 09 Jan 2025 15:21:00 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, DELETE, PUT
Access-Control-Allow-Headers: Content-Type, api_key,
Authorization
Server: Jetty(9.2.9.v20150224)

{
"code": 200,
"type": "unknown",
"message": "9223372036854775713"
}

Example 2:
package specbuilder;

import static io.restassured.RestAssured.given;

import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import io.restassured.builder.RequestSpecBuilder;
import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.filter.log.LogDetail;
import io.restassured.http.ContentType;
import
io.restassured.specification.RequestSpecification;
import
io.restassured.specification.ResponseSpecification;

public class RequestAndResponseSpecBuilder {


RequestSpecification requestSpecification;

ResponseSpecification responseSpecification;

@BeforeClass
public void initRequestAndResponseSpecBuilder() {
RequestSpecBuilder requestSpecBuilder = new
RequestSpecBuilder();
requestSpecBuilder.setBaseUri("https://petstore.swagg
er.io");
requestSpecBuilder.setBasePath("/v2");
requestSpecBuilder.addHeader("Content-Type",
"application/json");
requestSpecBuilder.log(LogDetail.ALL);
requestSpecification =
requestSpecBuilder.build();

ResponseSpecBuilder responseSpecBuilder = new


ResponseSpecBuilder();

responseSpecBuilder.expectContentType(ContentType.JSO
N);
responseSpecBuilder.expectStatusCode(200);
responseSpecBuilder.log(LogDetail.ALL);
responseSpecification =
responseSpecBuilder.build();

@Test
public void createUser() {
given(requestSpecification)

.body("{\r\n" + " \"id\": 0,\r\n" +


" \"username\": \"restasssureduser\",\r\n"
+
" \"firstName\": \"Rest\",\r\n" +
" \"lastName\": \"Assured\",\r\n"
+
" \"email\": \"[email protected]\",\r\n" +
" \"password\": \"Test@1234\",\r\n"
+
" \"phone\": \"9876543210\",\r\n" +
" \"userStatus\": 0\r\n" + "}")

.when()

.post("user")
.then()

.spec(responseSpecification)

.extract()

.response();

Request method: POST


Request URI: https://petstore.swagger.io/v2/user
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: Accept=*/*
Content-Type=application/json
Cookies: <none>
Multiparts: <none>
Body:
{
"id": 0,
"username": "restasssureduser",
"firstName": "Rest",
"lastName": "Assured",
"email": "[email protected]",
"password": "Test@1234",
"phone": "9876543210",
"userStatus": 0
}
HTTP/1.1 200 OK
Date: Thu, 09 Jan 2025 15:24:37 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, DELETE, PUT
Access-Control-Allow-Headers: Content-Type, api_key,
Authorization
Server: Jetty(9.2.9.v20150224)

{
"code": 200,
"type": "unknown",
"message": "9223372036854775744"
}

Serialization and Deserialization for Complex json:

public class ComplexJsonRequestBody {

private String id;


private String type;
private String name;
private Double ppu;
private Batters batters = new Batters();
private List<Topping> topping = new
ArrayList<Topping>();
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPpu() {
return ppu;
}
public void setPpu(Double ppu) {
this.ppu = ppu;
}
public Batters getBatters() {
return batters;
}
public void setBatters(Batters batters) {
this.batters = batters;
}
public List<Topping> getTopping() {
return topping;
}
public void setTopping(List<Topping> topping) {
this.topping = topping;
}

public class Batters {

private List<Batter> batter = new


ArrayList<Batter>();

public List<Batter> getBatter() {


return batter;
}

public void setBatter(List<Batter> batter) {


this.batter = batter;
}

public class Batter {

private Object id;


private String type;
public Object getId() {
return id;
}
public void setId(Object id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}

}
public class Topping {

private String id;


private String type;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}

public class ResponseBody {

private String message;


public String getMessage() {
return message;
}

public void setMessage(String message) {


this.message = message;
}

public class SendComplexJson {

@Test
public void sendComplexJson() {
ComplexJsonRequestBody requestBody = new
ComplexJsonRequestBody();

requestBody.setId("0001");
requestBody.setType("donut");
requestBody.setName("Cake");
requestBody.setPpu(0.55);
Batters battersObject =
requestBody.getBatters();

List<Batter> batterObject =
battersObject.getBatter();

Batter ele1 = new Batter();

ele1.setId("1001");
ele1.setType("Regular");

Batter ele2 = new Batter();

Object[] ele = new Object[2];

ele[0] = 5;
ele[1] = 9;

ele2.setId(ele);

ele2.setType("Chocolate");

batterObject.add(ele1);

batterObject.add(ele2);

List<Topping> toppingObject =
requestBody.getTopping();

Topping top1 = new Topping();

top1.setId("5001");
top1.setType("None");

Topping top2 = new Topping();

top2.setId("5002");
top2.setType("Glazed");

Topping top3 = new Topping();

top3.setId("5005");
top3.setType("Sugar");

toppingObject.add(top1);
toppingObject.add(top2);
toppingObject.add(top3);

RestAssured.baseURI = "https://82ac28ee-c468-
42d4-b652-5ac5aed990f8.mock.pstmn.io";

Response finalResp = given()

.header("Content-Type", "application/json")

.header("x-mock-match-request-body", "true")

.body(requestBody)
.log().all()

.when()

.post("att23novcomplexjson")

.then()

.log().all()

.extract()

.response();

ResponseBody respBody =
finalResp.as(ResponseBody.class);

String respMessage = respBody.getMessage();

System.out.println(respMessage);

Assert.assertEquals(respMessage, "Request body


matched with the example");

Output:
Request method: POST
Request URI: https://82ac28ee-c468-42d4-b652-
5ac5aed990f8.mock.pstmn.io/att23novcomplexjson
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: x-mock-match-request-body=true
Accept=*/*
Content-Type=application/json
Cookies: <none>
Multiparts: <none>
Body:
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters": {
"batter": [
{
"id": "1001",
"type": "Regular"
},
{
"id": [
5,
9
],
"type": "Chocolate"
}
]
},
"topping": [
{
"id": "5001",
"type": "None"
},
{
"id": "5002",
"type": "Glazed"
},
{
"id": "5005",
"type": "Sugar"
}
]
}
HTTP/1.1 201 Created
Date: Tue, 14 Jan 2025 14:11:37 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 60
Connection: keep-alive
x-srv-trace: v=1;t=d30481c4e4d1e295
x-srv-span: v=1;s=406be2cfe30508d1
Access-Control-Allow-Origin: *
X-RateLimit-Limit: 120
X-RateLimit-Remaining: 119
X-RateLimit-Reset: 1735917814
ETag: W/"96-S/5iQ2y1qqIInh5BwoPc+chvDJU"
Vary: Accept-Encoding

{
"message": "Request body matched with the
example"
}
Request body matched with the example

Authentication and Authorization:


Authentication: It is a process to verify the
identity with respect to the server and if it is
valid then we can say user is authenticated.

Authorization: If a set of service is allowed to be


used by an identity then it can be termed as
authorization for that user.

There are multiple authorization schemes available


which can be implemented:
Postman API:
https://www.postman.com/postman/published-postman-
templates/request/mj0cy1z/basic-auth
1. Basic Auth: In this we send an http request to the
server with an authorization header. This header
contains the word basic followed by a space and a
base 64 encoded string of format username:password.
This is an insecure because in the request the
username and password is available which travels over
the network that can lead to high chance of
compromise.

Example:
@Test
public void getAuthenticated()
{
RestAssured.baseURI = "https://postman-
echo.com";

Response resp = given()

.header("Authorization", "Basic
cG9zdG1hbjpwYXNzd29yZA==")

.log().all()

.when()

.get("basic-auth")

.then()

.log().all()

.extract()

.response();

Alternate way to write the code in restasssured:


@Test
public void getAuthenticated() {
RestAssured.baseURI = "https://postman-
echo.com";

Response resp = given()

// .header("Authorization", "Basic
cG9zdG1hbjpwYXNzd29yZA==")

.auth()

.basic("postman", "password")

.log().all()

.when()

.get("basic-auth")

.then()

.log().all()

.extract()

.response();

Output:
Request method: GET
Request URI: https://postman-echo.com/basic-auth
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: Accept=*/*
Cookies: <none>
Multiparts: <none>
Body: <none>
HTTP/1.1 200 OK
Date: Tue, 14 Jan 2025 14:52:11 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 27
Connection: keep-alive
Server: nginx
ETag: W/"1b-o64KRFi1Uw+73hnrS1UFKUVInOY"
set-cookie: sails.sid=s
%3ANqZwlkLvBSBrJDVqZ4frfuJTMrU7X2dh.TTVFBi2bCNb3HOnlq
uJGrwsxaK6%2BcgpRE6XlNqcVl9k; Path=/; HttpOnly

{
"authenticated": true
}

Output:
Request method: GET
Request URI: https://postman-echo.com/basic-auth
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: Authorization=Basic
cG9zdG1hbjpwYXNzd29yZA==
Accept=*/*
Cookies: <none>
Multiparts: <none>
Body: <none>
HTTP/1.1 200 OK
Date: Tue, 14 Jan 2025 14:37:43 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 27
Connection: keep-alive
Server: nginx
ETag: W/"1b-o64KRFi1Uw+73hnrS1UFKUVInOY"
set-cookie: sails.sid=s
%3AeTjWSNqbUmU968DO2K3VB0M7uaWl7k5H.a
%2FhuPqaUNHQThePQ%2Bfwz7MDMGpTobG75Btl2J12gssA;
Path=/; HttpOnly

{
"authenticated": true
}

Digest: It is more secure authentication method as


compare to Basic auth. In this credentials will also
be the part of request along with the hash of global
variable to make the probability to decrypt the
credentials of the user using an algorithm called as
MD5.
Example:
@Test
public void getAuthenticated() {
RestAssured.baseURI = "https://postman-
echo.com";

Response resp = given()

// .header("Authorization", "Basic
cG9zdG1hbjpwYXNzd29yZA==")

.auth()

.basic("postman", "password")

.log().all()

.when()

.get("basic-auth")

.then()

.log().all()

.extract()
.response();

Output:
Request method: GET
Request URI: https://postman-echo.com/digest-auth
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: Accept=*/*
Cookies: <none>
Multiparts: <none>
Body: <none>
HTTP/1.1 200 OK
Date: Tue, 14 Jan 2025 15:10:04 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 27
Connection: keep-alive
Server: nginx
ETag: W/"1b-o64KRFi1Uw+73hnrS1UFKUVInOY"
set-cookie: sails.sid=s
%3AClK8jNcWEmGe0IZ3afpYdU7zRftCtcvx.hquiqsgF6JdPp2BQj
Y1HbyKjoTonqaUNMKgcDeS29xA; Path=/; HttpOnly

{
"authenticated": true
}

API Key: It is scheme to perform the authentication


and authorization based on a security String format
token that allows user to interact with the system.
For any third party application if we use it inside
the code base then to integrate it we mostly use API
Key.

Workspace API’s:
https://www.postman.com/postman/published-postman-
templates/folder/kua789n/workspaces

Steps to create the API key for postman:


1. Go to the avatar image and click on view profile

2. Click on edit profile:


3. Click on API key

4. Click on generate API key button


5. Type the name of key and click on generate:

Example:

@Test
public void createWorkspace()
{
RestAssured.baseURI =
"https://api.getpostman.com";

given()

.body("{\r\n"
+ " \"workspace\": {\r\n"
+ " \"name\": \"Workspace
Two\",\r\n"
+ " \"type\": \"personal\",\
r\n"
+ " \"description\": \"This
is a test workspace\"\r\n"
+ " }\r\n"
+ "}")
.header("Content-Type", "application/json")

.header("x-api-key", "PMAK-
6787c14f646c180001649433-
4c76eb73fdf247b282c63a401c1fc62507")

.log().all()

.when()

.post("workspaces")

.then()

.log().all()

.extract()

.response();
}

Output:
Request method: POST
Request URI: https://api.getpostman.com/workspaces
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: x-api-key=PMAK-6787c14f646c180001649433-
4c76eb73fdf247b282c63a401c1fc62507
Accept=*/*
Content-Type=application/json
Cookies: <none>
Multiparts: <none>
Body:
{
"workspace": {
"name": "Workspace Two",
"type": "personal",
"description": "This is a test workspace"
}
}
HTTP/1.1 200
Date: Wed, 15 Jan 2025 14:24:15 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 82
Connection: keep-alive
Server: nginx
x-frame-options: deny
x-xss-protection: 1; mode=block
x-content-type-options: nosniff
referrer-policy: no-referrer-when-downgrade
access-control-allow-origin: *
access-control-allow-methods: GET,POST,PUT,DELETE
access-control-allow-headers: content-type,x-api-key
access-control-allow-credentials: false
x-ratelimit-limit: 300
x-ratelimit-reset: 59
x-ratelimit-remaining: 299
ratelimit: limit=300, remaining=299, reset=59
ratelimit-policy: 300;w=60
ratelimit-limit: 300
ratelimit-remaining: 299
ratelimit-reset: 59
ratelimit-limit-month: 10000
ratelimit-remaining-month: 9994
x-ratelimit-limit-month: 10000
x-ratelimit-remaining-month: 9994
uWebSockets: 20

{
"workspace": {
"id": "d00378f4-2c58-47fb-922e-2c5116176b74",
"name": "Workspace Two"
}
}

Example 2:
@Test
public void deleteWorkspace()
{
RestAssured.baseURI =
"https://api.getpostman.com";

given()

.header("x-api-key", "PMAK-
6787c14f646c180001649433-
4c76eb73fdf247b282c63a401c1fc62507")

.log().all()

.when()

.delete("workspaces/bd441a1d-7648-410c-85d4-
04617fc22b1c")

.then()

.log().all()

.extract()

.response();
}

Output:
Request method: DELETE
Request URI:
https://api.getpostman.com/workspaces/bd441a1d-
7648-410c-85d4-04617fc22b1c
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: x-api-key=PMAK-6787c14f646c180001649433-
4c76eb73fdf247b282c63a401c1fc62507
Accept=*/*
Cookies: <none>
Multiparts: <none>
Body: <none>
HTTP/1.1 200
Date: Wed, 15 Jan 2025 14:43:20 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 59
Connection: keep-alive
Server: nginx
x-frame-options: deny
x-xss-protection: 1; mode=block
x-content-type-options: nosniff
referrer-policy: no-referrer-when-downgrade
access-control-allow-origin: *
access-control-allow-methods: GET,POST,PUT,DELETE
access-control-allow-headers: content-type,x-api-key
access-control-allow-credentials: false
x-ratelimit-limit: 300
x-ratelimit-reset: 59
x-ratelimit-remaining: 299
ratelimit: limit=300, remaining=299, reset=59
ratelimit-policy: 300;w=60
ratelimit-limit: 300
ratelimit-remaining: 299
ratelimit-reset: 59
ratelimit-limit-month: 10000
ratelimit-remaining-month: 9991
x-ratelimit-limit-month: 10000
x-ratelimit-remaining-month: 9991
uWebSockets: 20

{
"workspace": {
"id": "bd441a1d-7648-410c-85d4-04617fc22b1c"
}
}

Bearer token: It is an auth scheme used in API


security where the client send a token (String) in
the request to authenticate. In bearer token we can
also define the scope of a particular token through
we can define how many services are applicable using
a specific.

Documentation for API of github


https://docs.github.com/en/rest/repos/repos?
apiVersion=2022-11-28#create-a-repository-for-the-
authenticated-user
All the git api works on bearer token that can be
create using following steps:
1. Go to avatar menu and click on settings

2. Click on developer setting


3. Click on personal access token:

4. Click on token classic

5. Click on generate new token followed by token


classic
Create repository using RestAssured:
@Test
public void createRepo() {
RestAssured.baseURI =
"https://api.github.com/";

given()

.body("{\r\n" + " \"name\": \"ATT


23Nov Repository creation test using Restassured\",\
r\n"
+
" \"description\": \"This is my test
Repository\",\r\n"
+
" \"homepage\": \"https://github.com\",\r\n" + "
\"private\": true,\r\n"
+ " \"is_template\":
false\r\n" + "}")

.header("Accept",
"application/vnd.github+json")
.header("Authorization", "Bearer
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")
.header("X-GitHub-Api-Version",
"2022-11-28")

.log().all().when()

.post("user/repos")

.then()

.log().all()

.extract()

.response();

}
}
Output:
Request method: POST
Request URI: https://api.github.com/user/repos
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: Accept=application/vnd.github+json
Authorization=Bearer
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
X-GitHub-Api-Version=2022-11-28
Content-Type=text/plain;
charset=ISO-8859-1
Cookies: <none>
Multiparts: <none>
Body:
{
"name": "ATT 23Nov Repository creation test using
Restassured",
"description": "This is my test Repository",
"homepage": "https://github.com",
"private": true,
"is_template": false
}
HTTP/1.1 201 Created
Date: Thu, 16 Jan 2025 14:58:15 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 7692
Cache-Control: private, max-age=60, s-maxage=60
Vary: Accept, Authorization, Cookie, X-GitHub-
OTP,Accept-Encoding, Accept, X-Requested-With
ETag:
"5a75a3ebdbbcaf413ab506e97dc53e0ec7aa80d3ce5dd5b451a3
6f95ff948d17"
X-OAuth-Scopes: admin:enterprise, admin:gpg_key,
admin:org, admin:org_hook, admin:public_key,
admin:repo_hook, admin:ssh_signing_key, audit_log,
codespace, copilot, delete:packages, gist,
notifications, project, repo, user, workflow,
write:discussion, write:packages
X-Accepted-OAuth-Scopes: public_repo, repo
github-authentication-token-expiration: 2025-02-15
14:40:18 UTC
Location:
https://api.github.com/repos/gouravjawale100/ATT-
23Nov-Repository-creation-test-using-Restassured
X-GitHub-Media-Type: github.v3; format=json
x-github-api-version-selected: 2022-11-28
X-RateLimit-Limit: 5000
X-RateLimit-Remaining: 4997
X-RateLimit-Reset: 1737042104
X-RateLimit-Used: 3
X-RateLimit-Resource: core
Access-Control-Expose-Headers: ETag, Link, Location,
Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-
RateLimit-Remaining, X-RateLimit-Used, X-RateLimit-
Resource, X-RateLimit-Reset, X-OAuth-Scopes, X-
Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-
Media-Type, X-GitHub-SSO, X-GitHub-Request-Id,
Deprecation, Sunset
Access-Control-Allow-Origin: *
Strict-Transport-Security: max-age=31536000;
includeSubdomains; preload
X-Frame-Options: deny
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Referrer-Policy: origin-when-cross-origin, strict-
origin-when-cross-origin
Content-Security-Policy: default-src 'none'
Server: github.com
X-GitHub-Request-Id: 0DB9:39DF8A:96B0:B192:67891E85

{
"id": 917737741,
"node_id": "R_kgDONrORDQ",
"name": "ATT-23Nov-Repository-creation-test-
using-Restassured",
"full_name": "gouravjawale100/ATT-23Nov-
Repository-creation-test-using-Restassured",
"private": true,
"owner": {
"login": "gouravjawale100",

}
Assertions in RestAssured @Test
public void assertData() {

{
RestAssured.baseURI =
"https://api.getpostman.com";

given()

.header("x-api-key", "PMAK-
678a64fac2307b000101ce47-
fcb1f3a2c10b29d0b9598aba98beb7a6f5")

.log().all()

.when()

.get("workspaces")

.then()

.statusCode(200)// validate the status


code if it is 200 or not

.header("Content-Type",
"application/json; charset=utf-8")

.body("workspaces[1].id",
equalTo("8e12339e-b561-4326-90db-29384205056e")) //
if a path contains specific value

.body(containsString("8e12339e-b561-
4326-90db-29384205056e")) // if complete response has
a String present

.body("workspaces[1]",
hasKey("createdBy")) // if the defined path has a
specific key then it will pass
.body("workspaces[4]", hasEntry("id",
"2a2df301-4bcb-4e1c-afa6-25ab7285104a")) // if
specific path has a valid key-value pair

.body("workspaces.name", hasItems("Test
workspaceevening","Latest workspace123"))//if the
provided values got matched then it will pass
otherwise fail

.body("workspaces.name", contains("Team
Workspace", "My Workspace", "ModifyingTest
Workspace", "ATTObjectWorkspace", "Manual Workspace",
"Latest workspace123", "ATT batch Workspace2", "Test
workspaceevening", "ATT30AugRestAssuredWorkspace",
"TestDataFromResponse", "RestAssured workspace",
"RestAssured workspace", "RestAssured workspace",
"Manually created workspace", "workspace created
through restassured", "updated ATT morning
restassured", "ATT morning restassured post request",
"workspacecreated using postman",
"ATT20JanWorkspace", "UpdatedworkspaceATT20Jan",
"ATT20RestAssuredWorkspace", "ATT20JanWorkspace3",
"latestFeb23RestAssuredWorkspace", "modified
workspace name ATT 6Apr", "Restassured workspace 29
May", "ATT11MayWorkspace by RestAssured",
"ATT11MayWorkspace by RestAssured",
"ATT11MayWorkspace by RestAssured", "Updated
ATT11MayWorkspaceLatest by Code", "Restassured
workspace 29 May", "ATT13July workspace",
"ATT13JulyWorkspace Postman", "ATT13JulyWorkspace-
RestAssured", "Manualtestingworkspacecreation",
"ATT28SeptWorkspace", "ATT28SeptWorkspaceMorning",
"ATT28SeptWorkspaceMorningByRestAssured",
"ATT28SeptWorkspaceMorningByRestAssured", "New
Workspace created manually", "New Workspace created
manually", "Workspace Two"))
// contains method will not only
check the content of all the provided names along
with the sequence of data

.body("workspaces.name",
containsInAnyOrder( "My Workspace", "ModifyingTest
Workspace", "Team Workspace", "ATTObjectWorkspace",
"Manual Workspace", "Latest workspace123", "ATT batch
Workspace2", "Test workspaceevening",
"ATT30AugRestAssuredWorkspace",
"TestDataFromResponse", "RestAssured workspace",
"RestAssured workspace", "RestAssured workspace",
"Manually created workspace", "workspace created
through restassured", "updated ATT morning
restassured", "ATT morning restassured post request",
"workspacecreated using postman",
"ATT20JanWorkspace", "UpdatedworkspaceATT20Jan",
"ATT20RestAssuredWorkspace", "ATT20JanWorkspace3",
"latestFeb23RestAssuredWorkspace", "modified
workspace name ATT 6Apr", "Restassured workspace 29
May", "ATT11MayWorkspace by RestAssured",
"ATT11MayWorkspace by RestAssured",
"ATT11MayWorkspace by RestAssured", "Updated
ATT11MayWorkspaceLatest by Code", "Restassured
workspace 29 May", "ATT13July workspace",
"ATT13JulyWorkspace Postman", "ATT13JulyWorkspace-
RestAssured", "Manualtestingworkspacecreation",
"ATT28SeptWorkspace", "ATT28SeptWorkspaceMorning",
"ATT28SeptWorkspaceMorningByRestAssured",
"ATT28SeptWorkspaceMorningByRestAssured", "New
Workspace created manually", "New Workspace created
manually", "Workspace Two"))

// containsInAnyOrder method will only


check the content of all the provided names but not
the sequence of data

.body("workspaces", hasSize(41))// it
will verify if the provided size of array is equal or
not

.log().all();
}

Note: In the above we need to import class – Matchers


class in a static manner
Use of log method:
1. log().all():
This will print everything on the console related to
the elements that are being send as a part of request
(if use it in request section) also print the
response if we use it inside then section.
@Test
public void getSingleUserDetail()
{
baseURI = "https://reqres.in";

Response resp = given()

.log().all()

.when()

.get("api/users/2")

.then()

.log().all()

.extract()// to extract the properties of


response

.response();

Request method: GET


Request URI: https://reqres.in/api/users/2
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: Accept=*/*
Cookies: <none>
Multiparts: <none>
Body: <none>
HTTP/1.1 200 OK
Date: Fri, 17 Jan 2025 14:52:20 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Report-To: {"group":"heroku-
nel","max_age":3600,"endpoints":[{"url":"https://
nel.heroku.com/reports?ts=1737093901&sid=c4c9725f-
1ab0-44d8-820f-430df2718e11&s=ianbRAjXJiFBZqkHIZn
%2F54osnCDOVn75Bn7PXb2k6Ic%3D"}]}
Reporting-Endpoints:
heroku-nel=https://nel.heroku.com/reports?
ts=1737093901&sid=c4c9725f-1ab0-44d8-820f-
430df2718e11&s=ianbRAjXJiFBZqkHIZn
%2F54osnCDOVn75Bn7PXb2k6Ic%3D
Nel: {"report_to":"heroku-
nel","max_age":3600,"success_fraction":0.005,"failure
_fraction":0.05,"response_headers":["Via"]}
X-Powered-By: Express
Access-Control-Allow-Origin: *
Etag: W/"152-ApQgGHL6RKwaebFlrPCYPBO1xHg"
Via: 1.1 vegur
Cache-Control: max-age=14400
CF-Cache-Status: HIT
Age: 2835
Vary: Accept-Encoding
Server: cloudflare
CF-RAY: 90372b270e7c2ffe-BOM
Content-Encoding: gzip
server-timing: cfL4;desc="?
proto=TCP&rtt=7945&min_rtt=7940&rtt_var=2988&sent=7&r
ecv=7&lost=0&retrans=0&sent_bytes=3107&recv_bytes=770
&delivery_rate=530561&cwnd=252&unsent_bytes=0&cid=531
d034112d7e3c6&ts=466&x=0"

{
"data": {
"id": 2,
"email": "[email protected]",
"first_name": "Janet",
"last_name": "Weaver",
"avatar": "https://reqres.in/img/faces/2-
image.jpg"
},
"support": {
"url": "https://contentcaddy.io?
utm_source=reqres&utm_medium=json&utm_campaign=referr
al",
"text": "Tired of writing endless social
media content? Let Content Caddy generate it for
you."
}
}

2. body(): This will only print the body content of


the request / response based on the usage.
@Test
public void getSingleUserDetail()
{
baseURI = "https://reqres.in";

Response resp = given()

.log().body()

.when()

.get("api/users/2")

.then()

.log().body()

.extract()// to extract the properties of


response

.response();

}
Output:
Body: <none>
{
"data": {
"id": 2,
"email": "[email protected]",
"first_name": "Janet",
"last_name": "Weaver",
"avatar": "https://reqres.in/img/faces/2-
image.jpg"
},
"support": {
"url": "https://contentcaddy.io?
utm_source=reqres&utm_medium=json&utm_campaign=referr
al",
"text": "Tired of writing endless social
media content? Let Content Caddy generate it for
you."
}
}

3. uri() and headers(): To print the uri from the


request and headers from the response we can use it
as below
@Test
public void getSingleUserDetail()
{
baseURI = "https://reqres.in";

Response resp = given()

.log().uri()

.when()

.get("api/users/2")
.then()

.log().headers()

.extract()// to extract the properties of


response

.response();

Output:
Request URI: https://reqres.in/api/users/2
Date: Fri, 17 Jan 2025 14:59:15 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Report-To: {"group":"heroku-
nel","max_age":3600,"endpoints":[{"url":"https://
nel.heroku.com/reports?ts=1737093901&sid=c4c9725f-
1ab0-44d8-820f-430df2718e11&s=ianbRAjXJiFBZqkHIZn
%2F54osnCDOVn75Bn7PXb2k6Ic%3D"}]}
Reporting-Endpoints:
heroku-nel=https://nel.heroku.com/reports?
ts=1737093901&sid=c4c9725f-1ab0-44d8-820f-
430df2718e11&s=ianbRAjXJiFBZqkHIZn
%2F54osnCDOVn75Bn7PXb2k6Ic%3D
Nel: {"report_to":"heroku-
nel","max_age":3600,"success_fraction":0.005,"failure
_fraction":0.05,"response_headers":["Via"]}
X-Powered-By: Express
Access-Control-Allow-Origin: *
Etag: W/"152-ApQgGHL6RKwaebFlrPCYPBO1xHg"
Via: 1.1 vegur
Cache-Control: max-age=14400
CF-Cache-Status: HIT
Age: 3250
Vary: Accept-Encoding
Server: cloudflare
CF-RAY: 903735440d9df563-BOM
Content-Encoding: gzip
server-timing: cfL4;desc="?
proto=TCP&rtt=6123&min_rtt=5917&rtt_var=2631&sent=7&r
ecv=7&lost=0&retrans=0&sent_bytes=3106&recv_bytes=770
&delivery_rate=559873&cwnd=188&unsent_bytes=0&cid=4f9
750c846de9838&ts=387&x=0"

4. ifValidationFails(): This method will print all


logs only when there is a validation failure happens
and we want to log the details of request.

@Test
public void getSingleUserDetail()
{
baseURI = "https://reqres.in";

Response resp = given()

.log().ifValidationFails()

.when()

.get("api/users/2")

.then()

.assertThat()

.log().headers()

.statusCode(300)

.extract()// to extract the properties of


response

.response();

}
}
Output:
Date: Fri, 17 Jan 2025 15:04:41 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Report-To: {"group":"heroku-
nel","max_age":3600,"endpoints":[{"url":"https://
nel.heroku.com/reports?ts=1737093901&sid=c4c9725f-
1ab0-44d8-820f-430df2718e11&s=ianbRAjXJiFBZqkHIZn
%2F54osnCDOVn75Bn7PXb2k6Ic%3D"}]}
Reporting-Endpoints:
heroku-nel=https://nel.heroku.com/reports?
ts=1737093901&sid=c4c9725f-1ab0-44d8-820f-
430df2718e11&s=ianbRAjXJiFBZqkHIZn
%2F54osnCDOVn75Bn7PXb2k6Ic%3D
Nel: {"report_to":"heroku-
nel","max_age":3600,"success_fraction":0.005,"failure
_fraction":0.05,"response_headers":["Via"]}
X-Powered-By: Express
Access-Control-Allow-Origin: *
Etag: W/"152-ApQgGHL6RKwaebFlrPCYPBO1xHg"
Via: 1.1 vegur
Cache-Control: max-age=14400
CF-Cache-Status: HIT
Age: 3576
Vary: Accept-Encoding
Server: cloudflare
CF-RAY: 90373d39ea7e3b03-BOM
Content-Encoding: gzip
server-timing: cfL4;desc="?
proto=TCP&rtt=8406&min_rtt=7947&rtt_var=3900&sent=7&r
ecv=7&lost=0&retrans=0&sent_bytes=3107&recv_bytes=770
&delivery_rate=364355&cwnd=250&unsent_bytes=0&cid=774
8188b847b7b07&ts=585&x=0"
Request method: GET
Request URI: https://reqres.in/api/users/2
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: Accept=*/*
Cookies: <none>
Multiparts: <none>
Body: <none>
FAILED: basics.GET_ListOfUsers.getSingleUserDetail
java.lang.AssertionError: 1 expectation failed.
Expected status code <300> but was <200>.

5. ifErrors(): This method is applicable for response


based logs and it print the logs only if the status
code of the request >399 (error specific status
code).
Example:
@Test
public void getSingleUserDetail()
{
baseURI = "https://reqres.in";

Response resp = given()

.log().all()

.when()

.get("api/users/2/sgdadgkajsgdasgdjgsadjsa")

.then()

.assertThat()

.log().ifError()

.statusCode(200)

.extract()// to extract the properties of


response

.response();
}
}

Output:
Request method: GET
Request URI:

https://reqres.in/api/users/2/sgdadgkajsgdasgdjgsadjs
a
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: Accept=*/*
Cookies: <none>
Multiparts: <none>
Body: <none>
HTTP/1.1 404 Not Found
Date: Fri, 17 Jan 2025 15:12:47 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 2
Connection: keep-alive
Report-To: {"group":"heroku-
nel","max_age":3600,"endpoints":[{"url":"https://
nel.heroku.com/reports?ts=1737126767&sid=c4c9725f-
1ab0-44d8-820f-430df2718e11&s=VlKN2jWsmGo
%2FvHI7QJOnfI79Dx6n%2BavYAGObfFulPPs%3D"}]}
Reporting-Endpoints:
heroku-nel=https://nel.heroku.com/reports?
ts=1737126767&sid=c4c9725f-1ab0-44d8-820f-
430df2718e11&s=VlKN2jWsmGo%2FvHI7QJOnfI79Dx6n
%2BavYAGObfFulPPs%3D
Nel: {"report_to":"heroku-
nel","max_age":3600,"success_fraction":0.005,"failure
_fraction":0.05,"response_headers":["Via"]}
X-Powered-By: Express
Access-Control-Allow-Origin: *
Etag: W/"2-vyGp6PvFo4RvsFtPoIWeCReyIC8"
Via: 1.1 vegur
Cache-Control: max-age=14400
CF-Cache-Status: MISS
Vary: Accept-Encoding
Server: cloudflare
CF-RAY: 903749187d2646a7-BOM
server-timing: cfL4;desc="?
proto=TCP&rtt=8785&min_rtt=8507&rtt_var=3746&sent=7&r
ecv=7&lost=0&retrans=0&sent_bytes=3107&recv_bytes=795
&delivery_rate=394670&cwnd=252&unsent_bytes=0&cid=4e9
c98f078366568&ts=722&x=0"

Query and path param usage:


Query param:
1. using Query param ()

@Test
public void getListOfUsers() {

baseURI = "https://reqres.in";
Response resp = given()

.queryParam("page", "2")

.queryParam("line", "4")

.queryParam("word", "6")

.log().all()

.when()
.get("api/users")

.then()

.log().all()

.extract()

.response();

Output:
Request method: GET
Request URI: https://reqres.in/api/users?
page=2&line=4&word=6
Proxy: <none>
Request params: <none>
Query params: page=2
line=4
word=6
Form params: <none>
Path params: <none>
Headers: Accept=*/*
Cookies: <none>
Multiparts: <none>
Body: <none>
HTTP/1.1 200 OK
Date: Fri, 17 Jan 2025 15:23:41 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Report-To: {"group":"heroku-
nel","max_age":3600,"endpoints":[{"url":"https://
nel.heroku.com/reports?ts=1737127421&sid=c4c9725f-
1ab0-44d8-820f-430df2718e11&s=dd6hqzA2Zp
%2FXZv1QLUVP3AsvBkSqEhWhqK5t9YKqpm8%3D"}]}
Reporting-Endpoints:
heroku-nel=https://nel.heroku.com/reports?
ts=1737127421&sid=c4c9725f-1ab0-44d8-820f-
430df2718e11&s=dd6hqzA2Zp
%2FXZv1QLUVP3AsvBkSqEhWhqK5t9YKqpm8%3D
Nel: {"report_to":"heroku-
nel","max_age":3600,"success_fraction":0.005,"failure
_fraction":0.05,"response_headers":["Via"]}
X-Powered-By: Express
Access-Control-Allow-Origin: *
Etag: W/"440-ZjsmMKR8P3usr2uJZbOCGCxC3Uw"
Via: 1.1 vegur
Cache-Control: max-age=14400
CF-Cache-Status: MISS
Vary: Accept-Encoding
Server: cloudflare
CF-RAY: 9037590c5b2b3e15-BOM
Content-Encoding: gzip
server-timing: cfL4;desc="?
proto=TCP&rtt=7468&min_rtt=7408&rtt_var=2899&sent=7&r
ecv=7&lost=0&retrans=0&sent_bytes=3107&recv_bytes=789
&delivery_rate=536610&cwnd=250&unsent_bytes=0&cid=933
fa1e92320eddf&ts=784&x=0"

{
"page": 2,
"per_page": 6,
"total": 12,
"total_pages": 2,
}

2. QueryParams() method:
@Test
public void getListOfUsers() {

baseURI = "https://reqres.in";
Response resp = given()

// .queryParam("page", "2")
//
// .queryParam("line", "4")
//
// .queryParam("word", "6")

.queryParams("page", "2", "line",


"4", "word", "6")
.log().all()

.when()

.get("api/users")

.then()

.log().all()

.extract()

.response();

}
Output:
Request method: GET
Request URI: https://reqres.in/api/users?
page=2&line=4&word=6
Proxy: <none>
Request params: <none>
Query params: page=2
line=4
word=6
Form params: <none>
Path params: <none>
Headers: Accept=*/*
Cookies: <none>
Multiparts: <none>
Body: <none>
HTTP/1.1 200 OK
Date: Fri, 17 Jan 2025 15:28:39 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Report-To: {"group":"heroku-
nel","max_age":3600,"endpoints":[{"url":"https://
nel.heroku.com/reports?ts=1737127421&sid=c4c9725f-
1ab0-44d8-820f-430df2718e11&s=dd6hqzA2Zp
%2FXZv1QLUVP3AsvBkSqEhWhqK5t9YKqpm8%3D"}]}
Reporting-Endpoints:
heroku-nel=https://nel.heroku.com/reports?
ts=1737127421&sid=c4c9725f-1ab0-44d8-820f-
430df2718e11&s=dd6hqzA2Zp
%2FXZv1QLUVP3AsvBkSqEhWhqK5t9YKqpm8%3D
Nel: {"report_to":"heroku-
nel","max_age":3600,"success_fraction":0.005,"failure
_fraction":0.05,"response_headers":["Via"]}
X-Powered-By: Express
Access-Control-Allow-Origin: *
Etag: W/"440-ZjsmMKR8P3usr2uJZbOCGCxC3Uw"
Via: 1.1 vegur
Cache-Control: max-age=14400
CF-Cache-Status: HIT
Age: 298
Vary: Accept-Encoding
Server: cloudflare
CF-RAY: 90376056b86140bd-BOM
Content-Encoding: gzip
server-timing: cfL4;desc="?
proto=TCP&rtt=8496&min_rtt=7900&rtt_var=4155&sent=7&r
ecv=7&lost=0&retrans=0&sent_bytes=3107&recv_bytes=789
&delivery_rate=334306&cwnd=252&unsent_bytes=0&cid=fcb
a4e639228341f&ts=408&x=0"

{
"page": 2,
"per_page": 6,
"total": 12,
"total_pages": 2,

3. using hashmap:

@Test
public void getListOfUsers() {
LinkedHashMap<String, String> hm = new
LinkedHashMap<String, String>();

hm.put("page", "2");
hm.put("line", "4");
hm.put("word", "6");

baseURI = "https://reqres.in";
Response resp = given()

// .queryParam("page", "2")
//
// .queryParam("line", "4")
//
// .queryParam("word", "6")

// .queryParams("page", "2", "line",


"4", "word", "6")

.queryParams(hm)

.log().all()

.when()

.get("api/users")

.then()

.log().all()

.extract()

.response();

}
Output:
Request method: GET
Request URI: https://reqres.in/api/users?
page=2&line=4&word=6
Proxy: <none>
Request params: <none>
Query params: page=2
line=4
word=6
Form params: <none>
Path params: <none>
Headers: Accept=*/*
Cookies: <none>
Multiparts: <none>
Body: <none>
HTTP/1.1 200 OK
Date: Fri, 17 Jan 2025 15:32:00 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Report-To: {"group":"heroku-
nel","max_age":3600,"endpoints":[{"url":"https://
nel.heroku.com/reports?ts=1737127421&sid=c4c9725f-
1ab0-44d8-820f-430df2718e11&s=dd6hqzA2Zp
%2FXZv1QLUVP3AsvBkSqEhWhqK5t9YKqpm8%3D"}]}
Reporting-Endpoints:
heroku-nel=https://nel.heroku.com/reports?
ts=1737127421&sid=c4c9725f-1ab0-44d8-820f-
430df2718e11&s=dd6hqzA2Zp
%2FXZv1QLUVP3AsvBkSqEhWhqK5t9YKqpm8%3D
Nel: {"report_to":"heroku-
nel","max_age":3600,"success_fraction":0.005,"failure
_fraction":0.05,"response_headers":["Via"]}
X-Powered-By: Express
Access-Control-Allow-Origin: *
Etag: W/"440-ZjsmMKR8P3usr2uJZbOCGCxC3Uw"
Via: 1.1 vegur
Cache-Control: max-age=14400
CF-Cache-Status: HIT
Age: 499
Vary: Accept-Encoding
Server: cloudflare
CF-RAY: 9037653d194740cf-BOM
Content-Encoding: gzip
server-timing: cfL4;desc="?
proto=TCP&rtt=7894&min_rtt=7599&rtt_var=3439&sent=7&r
ecv=7&lost=0&retrans=0&sent_bytes=3107&recv_bytes=789
&delivery_rate=425343&cwnd=251&unsent_bytes=0&cid=052
76e6eac57440f&ts=690&x=0"

{
"page": 2,
"per_page": 6,
"total": 12,
"total_pages": 2,}

Path parameter: This is a variable which is associated in the request


as a path value through which we can locate the path inside the
resource.
Example:

@Test
public void getSingleUserDetail() {
baseURI = "https://reqres.in";

Response resp = given()

.pathParam("pathParam1", "2")

.pathParam("pathParam2", "4")

.pathParam("pathParam3", "6")

.log().all()

.when()

.get
("api/users/{pathParam1}/{pathParam2}/{pathParam3}")

.then()
.log().all()

.extract()// to extract the


properties of response

.response();

}
Output:
Request method: GET
Request URI: https://reqres.in/api/users/2/4/6
Proxy: <none>
Request params: <none>

Example 2:
@Test
public void getSingleUserDetail() {
baseURI = "https://reqres.in";

Response resp = given()

// .pathParam("pathParam1", "2")
//
// .pathParam("pathParam2", "4")
//
// .pathParam("pathParam3", "6")

.pathParams("pathParam1","2",
"pathParam2", "4", "pathParam3", "6")

.log().all()

.when()

.get
("api/users/{pathParam1}/{pathParam2}/{pathParam3}")

.then()

.log().all()
.extract()// to extract the
properties of response

.response();

}
}

Output:
Request method: GET
Request URI: https://reqres.in/api/users/2/4/6
Proxy: <none>
Request params: <none>

Example 3:
@Test
public void getSingleUserDetail() {
baseURI = "https://reqres.in";

HashMap<String, String> hm = new


HashMap<String, String>();

hm.put("pathParam1", "2");
hm.put("pathParam2", "3");
hm.put("pathParam3", "4");

Response resp = given()

// .pathParam("pathParam1", "2")
//
// .pathParam("pathParam2", "4")
//
// .pathParam("pathParam3", "6")

// .pathParams("pathParam1","2",
"pathParam2", "4", "pathParam3", "6")

.pathParams(hm)
.log().all()

.when()

.get
("api/users/{pathParam1}/{pathParam2}/{pathParam3}")

.then()

.log().all()

.extract()// to extract the


properties of response

.response();

}
}

Output:
Request method: GET
Request URI: https://reqres.in/api/users/2/3/4
Proxy: <none>
JWT Token: It is a token used to transmit information
between the 2 entities for authentication ad
authorization purpose so that user can avail the
service by proving the identity using JWT token.
It has 3 parts:
1. Header – It contains the algorithm at which we had
created it.
2. Payload – contains the data to be shown to the
server so that we can display the identity.

3. Signature: It is used to verify the token


authenticity. It get generated by encoded header.
Complete JWT token : header.payload.signature

%3CmxGraphModel%3E%3Croot%3E%3CmxCell%20id%3D%220%22%2F%3E%3CmxCell%20id%3D%221%22%20parent%3D%220%22%2F%3E%3CmxCell%20id%3D%222%22%20value%3D%22%22%20style%3D%22edgeStyle%3DorthogonalEdgeStyle%3Brounded%3D0%3BorthogonalLoop%3D1%3BjettySize%3Dauto%3Bhtml%3D1%3B%22%20edge%3D%221%22%20source%3D%225%22%20target%3D%228%22%20parent%3D%221%22%3E%3CmxGeometry%20relative%3D%221%22%20as%3D%22geometry%22%2F%3E%3C%2FmxCell%3E%3CmxCell%20id%3D%223%22%20value%3D%22%22%20style%3D%22edgeStyle%3DorthogonalEdgeStyle%3Brounded%3D0%3BorthogonalLoop%3D1%3BjettySize%3Dauto%3Bhtml%3D1%3B%22%20edge%3D%221%22%20source%3D%225%22%20target%3D%228%22%20parent%3D%221%22%3E%3CmxGeometry%20relative%3D%221%22%20as%3D%22geometry%22%2F%3E%3C%2FmxCell%3E%3CmxCell%20id%3D
%224%22%20value%3D%22%22%20style%3D%22edgeStyle%3DorthogonalEdgeStyle%3Brounded%3D0%3BorthogonalLoop%3D1%3BjettySize%3Dauto%3Bhtml%3D1%3B%22%20edge%3D%221%22%20source%3D%225%22%20target%3D%2210%22%20parent%3D%221%22%3E%3CmxGeometry%20relative%3D%221%22%20as%3D%22geometry%22%2F%3E%3C%2FmxCell%3E%3CmxCell%20id%3D%225%22%20value%3D%22Zoomin%20application%22%20style%3D%22rounded%3D1%3BwhiteSpace%3Dwrap%3Bhtml%3D1%3B%22%20vertex%3D%221%22%20parent%3D%221%22%3E%3CmxGeometry%20x%3D%22140%22%20y%3D%2290%22%20width%3D%22120%22%20height%3D%2260%22%20as%3D%22geometry%22%2F%3E%3C%2FmxCell%3E%3CmxCell%20id%3D%226%22%20style%3D%22edgeStyle%3DorthogonalEdgeStyle%3Brounded%3D0%3BorthogonalLoop%3D1%3BjettySize%3Dauto%3Bhtml%3D1%3B%22%20edge%3D%221%22%20source
%3D%227%22%20target%3D%225%22%20parent%3D%221%22%3E%3CmxGeometry%20relative%3D%221%22%20as%3D%22geometry%22%2F%3E%3C%2FmxCell%3E%3CmxCell%20id%3D%227%22%20value%3D%22User%22%20style%3D%22shape%3DumlActor%3BverticalLabelPosition%3Dbottom%3BverticalAlign%3Dtop%3Bhtml%3D1%3BoutlineConnect%3D0%3BfontSize%3D17%3B%22%20vertex%3D%221%22%20parent%3D%221%22%3E%3CmxGeometry%20x%3D%22-90%22%20y%3D%2290%22%20width%3D%2230%22%20height%3D%2260%22%20as%3D%22geometry%22%2F%3E%3C%2FmxCell%3E%3CmxCell%20id%3D%228%22%20value%3D%22Enter%20the%20data%20manually%20and%20create%20the%20account%22%20style%3D%22whiteSpace%3Dwrap%3Bhtml%3D1%3Brounded%3D1%3B%22%20vertex%3D%221%22%20parent%3D%221%22%3E%3CmxGeometry%20x%3D%22320%22%20y%3D%2230%22%20width%3D
%22120%22%20height%3D%2260%22%20as%3D%22geometry%22%2F%3E%3C%2FmxCell%3E%3CmxCell%20id%3D%229%22%20value%3D%22%22%20style%3D%22edgeStyle%3DorthogonalEdgeStyle%3Brounded%3D0%3BorthogonalLoop%3D1%3BjettySize%3Dauto%3Bhtml%3D1%3B%22%20edge%3D%221%22%20source%3D%2210%22%20target%3D%2212%22%20parent%3D%221%22%3E%3CmxGeometry%20relative%3D%221%22%20as%3D%22geometry%22%2F%3E%3C%2FmxCell%3E%3CmxCell%20id%3D%2210%22%20value%3D%22Google%20app%22%20style%3D%22whiteSpace%3Dwrap%3Bhtml%3D1%3Brounded%3D1%3B%22%20vertex%3D%221%22%20parent%3D%221%22%3E%3CmxGeometry%20x%3D%22320%22%20y%3D%22150%22%20width%3D%22120%22%20height%3D%2260%22%20as%3D%22geometry%22%2F%3E%3C%2FmxCell%3E%3CmxCell%20id%3D%2211%22%20value%3D%22%22%20style%3D%22edgeStyle
%3DorthogonalEdgeStyle%3Brounded%3D0%3BorthogonalLoop%3D1%3BjettySize%3Dauto%3Bhtml%3D1%3B%22%20edge%3D%221%22%20source%3D%2212%22%20target%3D%2214%22%20parent%3D%221%22%3E%3CmxGeometry%20relative%3D%221%22%20as%3D%22geometry%22%2F%3E%3C%2FmxCell%3E%3CmxCell%20id%3D%2212%22%20value%3D%22Authentication%22%20style%3D%22whiteSpace%3Dwrap%3Bhtml%3D1%3Brounded%3D1%3B%22%20vertex%3D%221%22%20parent%3D%221%22%3E%3CmxGeometry%20x%3D%22320%22%20y%3D%22290%22%20width%3D%22120%22%20height%3D%2260%22%20as%3D%22geometry%22%2F%3E%3C%2FmxCell%3E%3CmxCell%20id%3D%2213%22%20style%3D%22edgeStyle%3DorthogonalEdgeStyle%3Brounded%3D0%3BorthogonalLoop%3D1%3BjettySize%3Dauto%3Bhtml%3D1%3BentryX%3D0.351%3BentryY%3D1.027%3BentryDx%3D0%3BentryDy%3D0%3BentryPerimeter
%3D0%3B%22%20edge%3D%221%22%20source%3D%2214%22%20target%3D%225%22%20parent%3D%221%22%3E%3CmxGeometry%20relative%3D%221%22%20as%3D%22geometry%22%2F%3E%3C%2FmxCell%3E%3CmxCell%20id%3D%2214%22%20value%3D%22Permission%22%20style%3D%22whiteSpace%3Dwrap%3Bhtml%3D1%3Brounded%3D1%3B%22%20vertex%3D%221%22%20parent%3D%221%22%3E%3CmxGeometry%20x%3D%22120%22%20y%3D%22290%22%20width%3D%22120%22%20height%3D%2260%22%20as%3D%22geometry%22%2F%3E%3C%2FmxCell%3E%3CmxCell%20id%3D%2215%22%20style%3D%22edgeStyle%3DorthogonalEdgeStyle%3Brounded%3D0%3BorthogonalLoop%3D1%3BjettySize%3Dauto%3Bhtml%3D1%3B%22%20edge%3D%221%22%20source%3D%2216%22%20target%3D%225%22%20parent%3D%221%22%3E%3CmxGeometry%20relative%3D%221%22%20as%3D%22geometry%22%2F%3E%3C%2FmxCell%3E
%3CmxCell%20id%3D%2216%22%20value%3D%22Google%20Server%22%20style%3D%22shape%3Dcylinder3%3BwhiteSpace%3Dwrap%3Bhtml%3D1%3BboundedLbl%3D1%3BbackgroundOutline%3D1%3Bsize%3D15%3B%22%20vertex%3D%221%22%20parent%3D%221%22%3E%3CmxGeometry%20x%3D%22210%22%20y%3D%22190%22%20width%3D%22100%22%20height%3D%2290%22%20as%3D%22geometry%22%2F%3E%3C%2FmxCell%3E%3CmxCell%20id%3D%2217%22%20value%3D%22Photos%22%20style%3D%22text%3Bhtml%3D1%3BstrokeColor%3Dnone%3BfillColor%3Dnone%3Balign%3Dcenter%3BverticalAlign%3Dmiddle%3BwhiteSpace%3Dwrap%3Brounded%3D0%3B%22%20vertex%3D%221%22%20parent%3D%221%22%3E%3CmxGeometry%20x%3D%22220%22%20y%3D%22190%22%20width%3D%2260%22%20height%3D%2230%22%20as%3D%22geometry%22%2F%3E%3C%2FmxCell%3E%3CmxCell%20id%3D%2218%22%20value%3D
%22%26lt%3Bb%26gt%3BOATH%202.0%26amp%3Bnbsp%3B%26lt%3B%2Fb%26gt%3B%22%20style%3D%22text%3Bhtml%3D1%3BstrokeColor%3Dnone%3BfillColor%3Dnone%3Balign%3Dcenter%3BverticalAlign%3Dmiddle%3BwhiteSpace%3Dwrap%3Brounded%3D0%3BfontSize%3D16%3B%22%20vertex%3D%221%22%20parent%3D%221%22%3E%3CmxGeometry%20x%3D%2270%22%20y%3D%22360%22%20width%3D%2290%22%20height%3D%2230%22%20as%3D%22geometry%22%2F%3E%3C%2FmxCell%3E%3C%2Froot%3E%3C%2FmxGraphModel%3E

OATH 2.0: OATH is an abbreviation for open authentication in which


we authorize third party app (google) to shared the defined
information to another application on the behalf of user and then
later on application will be able to access the data of user.

OATH 2.0:
Terminologies:
1. Client app: The application which send the request to get on the
behalf of user.
2. Authorization server: The server will allow the client app to use
the data of the user on post granting the permission.
3. Resource: The data that is to be shared is called as Resource.
4. Auth code: After acquiring the permission from user auth server
will send the auth code(short live token to the application so that
application can request for Refresh and Access token based on the
auth code.
Flow chart for OATH 2.0
1. User will go to client app (Zoomin app) in order to consume the
services.
2. Client app will redirect the user to Authorization server.
3. Authorization server will show login screen to the user so that user
can grant the permission to auth server inorder to access the data.
4. After granting the permission the auth server will share the short
live token i.e Auth code to the client app.
Note: Here in OATH 2.0 if the in step 4 the auth code is returned by
the client app as an acknowledgement then it is called as
Authorization grant flow whereas if the acknowledgement is not
provided by client app to the auth server then it is called as Implicit
grant flow.
5. Client app will send another request to the auth server so that as a
response auth server will return the refresh token and access token.
6. Based on the received access token client app will fetch the data
on the behalf of user.
To use the OATH 2.0 create an account for spotify:
1. Go to the url: https://open.spotify.com/
2. Click on signup / login followed by filling the form and create the
account

3. In the same window navigate to https://developer.spotify.com/

Creation of app:
1. Go to dashboard:

2. Accept the terms and condition:


3. Verify the identity based on email received by spotify

4. Click on create app button

5. Enter the details and create the application


Click on save button
5. Go to documentation and select WebAPI

Generation of Auth code:


1. Go to ‘Getting Started’ and go to Authorization code

You might also like