In this blog let learn about how to work with API, create our own Fake Local API and send Request to the server and get the response , we will work on all the Http Request Get, Post ,Put ,Patch and Delete .
REST assured Rest Assured is used to verify the REST APIs with the help of the Java library. Java library acts like a headless client to act upon the Rest web services. The libraries based on the Rest Assured library are also capable of validating the HTTP responses from the server.
Rest assured is java library for testing Restful Web services. It can be used to test XML & JSON based web services. It supports GET, POST, PUT, PATCH, DELETE, OPTIONS and HEAD requests and can be used to validate and verify the response of these requests.
TestNG
TestNG (Test Next Generation) is the testing framework.
TestNG makes automated tests more structured, readable, maintainable, and user-friendly. It provides powerful features and reporting. Its high-end annotations like dataprovider, makes it easier to scale up, as you perform cross browser testing across multiple devices, browsers, and their versions.
Maven Project Dependencies needed for RestAssured and TestNG
<dependencies>
<!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.3.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>
</dependency>
<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.rest-assured/json-schema-validator -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>5.3.0</version>
<scope>test</scope>
</dependency>
</dependencies>
Sample Get Request Code
When we Send request to the server , Server returns the response with Status Code and Status Line
package com.Reka.rest_assured_training;
import io.restassured.RestAssured;
import io.restassured.response.Response;
public class SampleGetRequest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Response response=RestAssured.get("http://www.google.co.in");
int statusCode=response.statusCode();
System.out.println(response.getStatusCode());
System.out.println(response.getTime());
String statusLine=response.statusLine();
System.out.println(statusCode);
System.out.println(statusLine);
}
}
Status Code for Successful Get :200
Console output which shows Status Code and Validation
Sample Get Request BDD method chaining
Rest Assured in BBD Style with the keywords Given , When and Then
package com.Reka.rest_assured_training;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
public class SampleGetRequestBDDmethodchaining
{
@Test
public void getRequestBDD()
{
baseURI="https://reqres.in/api";
ValidatableResponse response=
given()
.param(" ", " ")
.header(" "," ")
.when()
.get("/users/3")
.then()
.statusCode(200);
}
}
Console output
Get Request with Rest Assured TestNG
First Test Case to get the details of User 2
Second Test Case to get all the details in PAGE 2
package com.Reka.rest_assured_training;
import org.testng.Assert;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.response.ResponseBody;
public class SampleGetRequsetTestNG
{
@Test
public void getRequestTestNG()
{
Response response= RestAssured.get("https://reqres.in/api/users/2");
System.out.println(response.getTime());
System.out.println(response.getTime());
System.out.println(response.getStatusCode());
System.out.println(response.statusLine());
System.out.println(response.getHeader("content-type"));
ResponseBody responseBody=response.getBody();
System.out.println(responseBody.prettyPrint());
// ASSERTION
int statusCode=response.getStatusCode();
Assert.assertEquals(statusCode, 200);
}
@Test
public void test_1()
{
Response response=RestAssured.get("https://reqres.in/api/users?page=2");
System.out.println(response.getTime());
System.out.println(response.getTime());
System.out.println(response.getStatusCode());
System.out.println(response.statusLine());
System.out.println(response.getHeader("content-type"));
System.out.println(response.getBody().prettyPrint());
System.out.println(response.getBody().asString());
}
}
Console Output
Post Request
Here we have to send Request Body/ Request Pay load with the request in JSON format
Status Code for Successful Post :201
package com.Reka.rest_assured_training;
import java.util.HashMap;
import java.util.Map;
import org.json.simple.JSONObject;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.ValidatableResponse;
public class SamplePostRequest
{
@Test
public void testPost() {
JSONObject jsonObject=new JSONObject();
jsonObject.put("name", "Reka");
jsonObject.put( "job","SDET");
System.out.println(jsonObject.toString());
RestAssured.baseURI="https://reqres.in/api";
ValidatableResponse response=RestAssured
.given()
.header("Content-Type","application/json")
// [contentType(ContenTtype.JSON)
//.accept(ContenTtype.JSON)]
.body(jsonObject.toString())
.when()
.post("/users")
.then()
.statusCode(201).log().all();
}
}
Console Output
Put Request , Patch Request and Delete Request
Put Request : The HTTP PUT request method creates a new resource or replaces a representation of the target resource with the request payload.
Patch Request: A PATCH request is considered a set of instructions on how to modify a resource. Update the put
Delete Request :The HTTP DELETE method is used to delete a resource from the server. Unlike GET and HEAD requests, the DELETE requests may change the server state. You can send data to the server using URL parameters.
Here we have given Priority to run in order .
package com.Reka.rest_assured_training;
import org.json.simple.JSONObject;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import io.restassured.response.ValidatableResponse;
public class SamplePutRequest {
@Test(priority=1)
public void putRequestExample()
{
JSONObject jsonObject=new JSONObject();
jsonObject.put("name", "RekaNV");
jsonObject.put("job", "QC");
// text
System.out.println(jsonObject.toString());
//RestAssured.baseURI="https://reqres.in/api";
baseURI="https://reqres.in/api";
//ValidatableResponse response=RestAssured
given()
.header("", "")
//raw json as in postman
.body(jsonObject.toJSONString())
.when()
.put("/users/2")
.then()
.statusCode(200);
}
@Test(priority=2)
public void patchRequestExample()
{
JSONObject jsonObject=new JSONObject();
jsonObject.put("name", "RekaNV");
jsonObject.put("job", "SDET");
// text
System.out.println(jsonObject.toString());
//RestAssured.baseURI="https://reqres.in/api";
baseURI="https://reqres.in/api";
//ValidatableResponse response=RestAssured
given()
.header("Content-Type","application/json")
.header("", "")
//raw json as in postman
.body(jsonObject.toJSONString())
.when()
.patch("/users/2")
.then()
.statusCode(200);
}
@Test
public void deleteRequestExample()
{
//RestAssured.baseURI="https://reqres.in/api";
baseURI="https://reqres.in/api";
//ValidatableResponse response=RestAssured
//.given()
given()
.header("", "")
.when()
.delete("/users/2")
.then()
.statusCode(204);
}
}
Console Output
JSON Schema Validation
JSON File
Steps to follow for JSON Schema validation
1. Get API link and open in browser 2. Copy all 3. Open json to json converter link 4. Paste all from 2 into 3 => click generate schema=> schema will be generated , copy all 5. Got to target of the project => properties=> click folder icon=> go the target =>classes=> open rich text documenet and paste the schema and name as schema.json and save
package com.Reka.rest_assured_training;
import static io.restassured.RestAssured.baseURI;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
import org.testng.annotations.Test;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath; //***
public class ValidateJSONagainstSchema {
@Test
public void test3() {
baseURI="https://reqres.in/api";
given()
.get("/users?page=2")
.then()
.assertThat()
.body(matchesJsonSchemaInClasspath("schema.json")) //***
.statusCode(200);
}
}
Creating Fake API
Lets create our own API and learn.
Create db.json
{
"users": [
{
"id": 1,
"firstName": "Reka",
"lastName": "NV",
"subjectId": 1
},
{
"id": 2,
"firstName": "Raja",
"lastName": "NV",
"subjectId": 2
},
{
"id": 3,
"firstName": "Vasan",
"lastName": "NV",
"subjectId": 1
}
],
"subjects": [
{
"id": 1,
"name": "Automation"
},
{
"id": 2,
"name": "selenium"
}
]
}
Execute the command to run our Fake Local API in Server
json-server --watch db.json
Server is Up and Running
Keep the cmd prompt open while working with the request
you can cross check opening in the browser
http://localhost:3000, You will find all data you have written in db.json.
Click Users in Resources
Click Subjects in Resources
Working with our own Local API
Get , Post , Put , Patch and Delete Request
package com.Reka.rest_assured_training;
import static io.restassured.RestAssured.*;
import org.json.simple.JSONObject;
import org.testng.annotations.Test;
public class LocalAPIdb {
//RUN 1 BY 1
//@Test
@Test(priority=1)
public void getRequest() {
baseURI="http://localhost:3000";
given()
.get("/users")
.then()
.statusCode(200).log().all();
}
//@Test
@Test(priority=2)
public void postRequest() {
baseURI="http://localhost:3000";
JSONObject jsonobject=new JSONObject();
//jsonobject.put("id", 4); will be auto generated
jsonobject.put("firstName", "selvi");
jsonobject.put("lastName", "satish");
jsonobject.put("subjectId", 2);
System.out.println(jsonobject.toJSONString());
given()
.header("Content-Type","application/json")
.body(jsonobject.toJSONString())
.when()
.post("/users")
.then()
.statusCode(201).log().all();
}
//@Test
@Test(priority=3)
public void putRequest() {
baseURI="http://localhost:3000"; //update
JSONObject jsonobject=new JSONObject();
//jsonobject.put("id", 4); will be auto generated
jsonobject.put("firstName", "Arthi"); //
jsonobject.put("lastName", "Raj"); //
jsonobject.put("subjectId", 2);
System.out.println(jsonobject.toJSONString());
given()
.header("Content-Type","application/json")
.body(jsonobject.toJSONString())
.when()
.put("/users/4") //
.then()
.statusCode(200).log().all();
}
//@Test
@Test(priority=4)
public void patchRequest() {
baseURI="http://localhost:3000"; //update the put
JSONObject jsonobject=new JSONObject();
jsonobject.put("lastName", "Rajkumar"); //
System.out.println(jsonobject.toJSONString());
given()
.header("Content-Type","application/json")
.body(jsonobject.toJSONString())
.when()
.patch("/users/4") //
.then()
.statusCode(200).log().all();
}
//@Test
@Test(priority=5)
public void deleteRequest() {
baseURI="http://localhost:3000";
when()
.delete("/users/4")
.then()
.statusCode(200);
}
}
Console Output
Get Response
Post Response
Put Response
Patch Response
Delete Response
Conclusion:
I hope, This article will help you to understand how to work with RestAssured using TestNG .
You must have got an idea on the topics explained in this blog. Lets explore more and learn New Topics.
Happy Learning