This content originally appeared on DEV Community and was authored by Brijendra Rai
RestAssured library is used to automate RestAPIs.
Here is some key features of RestAssured which can revise your skills and may boast your code productivity with all new features.
Pre-requisites
Java 9+ and eclipse
TestNG
Maven
Dependencies
rest-assured
json-path
json
gson
testng
scribejava-api - to generate randon test data
json-schema-validator
xml-schema-validator
Static imports
io.restassured.RestAssured.*;
io.restassured.matcher.RestAssuredMatchers.*;
org.hamcrest.Matchers.*;
//or Json Schema
io.restassured.module.jsv.JsonSchemaValidator.*;
Http requests types and automation structure
given()
prerequisite
content-type, set cookies, ad auth, add param, set headers info etc.
when()
request
get, post, put, delete
then()
validation
validate status code, extract response, extract headers cookies and response body
Session 1 - Basic examples of get, post, put, delete
package day1;
import org.testng.annotations.Test;
import io.restassured.config.JsonConfig;
import io.restassured.config.RestAssuredConfig;
import io.restassured.path.json.config.JsonPathConfig.NumberReturnType;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import java.util.HashMap;
/*
given()
prerequisite
content-type, set cookies, ad auth, add param, set headers info etc.
when()
request
get, post, put, delete
then()
validation
validate status code, extract response, extract headers cookies and response body
*/
public class HTTPRequests {
int id;
@Test(priority = 1)
void getUser() {
given()
.when()
.get("https://reqres.in/api/users?page=2")
.then()
.statusCode(200)
.body("page", equalTo(2))
.log().all();
}
@Test(priority = 2)
void createUser() {
HashMap<String, String> data = new HashMap<String, String>();
data.put("name", "Maikal");
data.put("job", "Trainer");
id = given()
.config(RestAssuredConfig.config()
.jsonConfig(JsonConfig.jsonConfig().numberReturnType(NumberReturnType.BIG_DECIMAL)))
.contentType("application/json")
.body(data)
.when()
.post("https://reqres.in/api/users").jsonPath()
.getInt("id");
// .then()
// .statusCode(201)
// .log().all();
System.out.println("********* id= " + id);
}
@Test(priority = 3, dependsOnMethods = { "createUser" })
void updateUser() {
HashMap<String, String> data = new HashMap<String, String>();
data.put("name", "Maikal Kumar");
data.put("job", "Trainer");
given()
.contentType("application/json")
.body(data)
.when()
.put("https://reqres.in/api/users/" + id)
.then()
.statusCode(200).log().all();
}
@Test(priority = 4, dependsOnMethods = { "createUser" })
void deleteUser() {
given()
.when()
.delete("https://reqres.in/api/users/" + id)
.then()
.statusCode(204).log().all();
}
}
Session 2 - Creating Post Request Payloads in Multiple Ways
How many ways we create request body
1) Post request body using HashMap (not recomemded)
2) Post request body using using org.json (not recomemded)
3) Post request body using using POJO
4) Post request body using using external json file
package day2;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.HashMap;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.testng.annotations.Test;
import day2.pojo.Place;
import io.restassured.RestAssured;
/*
How many ways we create request body
1) Post request body using HashMap (not recomemded)
2) Post request body using using org.json (not recomemded)
3) Post request body using using POJO
4) Post request body using using external json file
* */
public class DiffWaysToCreateRequestBody {
// 1) Post request body using HashMap (not recommended)
//@Test
void testPostusingHashMap() {
RestAssured.baseURI = "https://rahulshettyacademy.com";
HashMap<String, Object> data = new HashMap<String, Object>();
HashMap<String, String> location = new HashMap<String, String>();
location.put("lat", "-38.383494");
location.put("lng", "33.427362");
data.put("location", location);
data.put("accuracy", 50);
data.put("name", "Frontline House");
data.put("phone_number", "(+91) 987 654 3210");
data.put("address", "29, side layout, cohen 09");
String types[] = { "shoe park", "shop", "sandles" };
data.put("types", types);
data.put("website", "https://google.com");
data.put("language", "French-IN");
String response = given()
.log().all()
.queryParam("key", "qaclick123")
//.header("Content-Type", "application/json") //use anyone
.contentType("application/json")
.body(data)
.when()
.post("maps/api/place/add/json")
.then()
.statusCode(200)
.body("scope", equalTo("APP"))
.header("server", "Apache/2.4.52 (Ubuntu)")
.extract().response().asString();
System.out.println("response: " + response);
}
// 2) Post request body using org.json library
/*
* Prerequisite library to add
* <dependency>
* <groupId>org.json</groupId>
* <artifactId>json</artifactId>
* <version>20230227</version>
* </dependency>
*
*/
//@Test
public void testPostUsingJsonLibrary() {
RestAssured.baseURI = "https://rahulshettyacademy.com";
HashMap<String, String> location = new HashMap<String, String>();
location.put("lat", "-38.383494");
location.put("lng", "33.427362");
JSONObject data = new JSONObject();
data.put("location", location);
data.put("accuracy", 50);
data.put("name", "Frontline House");
data.put("phone_number", "(+91) 987 654 3210");
data.put("address", "29, side layout, cohen 09");
String types[] = { "shoe park", "shop", "sandles" };
data.put("types", types);
data.put("website", "https://google.com");
data.put("language", "French-IN");
System.out.println("request body data: " + data.toString());
String response =
given()
.log().all()
.queryParam("key", "qaclick123")
.header("Content-Type", "application/json")
.contentType("application/json")
.body(data.toString())
.when()
.post("maps/api/place/add/json")
.then()
.statusCode(200)
.body("scope", equalTo("APP"))
.header("server", "Apache/2.4.52 (Ubuntu)")
.extract()
.response().asString();
System.out.println("response: " + response);
}
// 3) Post request body using POJO class
//@Test
public void testPostUsingPOJOClass() {
RestAssured.baseURI = "https://rahulshettyacademy.com";
Place data = new Place();
HashMap<String, String> location = new HashMap<String, String>();
location.put("lat", "-38.383494");
location.put("lng", "33.427362");
data.setLocation(location);
data.setAccuracy(50);
data.setName("Frontline House");
data.setPhone_number("(+91) 987 654 3210");
data.setAddress("29, side layout, cohen 09");
String types[] = { "shoe park", "shop", "sandles" };
data.setTypes(types);
data.setWebsite("https://google.com");
data.setLanguage("French-IN");
System.out.println("data: " + data.toString());
String response =
given()
.log().all()
.queryParam("key", "qaclick123")
.header("Content-Type", "application/json")
.contentType("application/json")
.body(data)
.when()
.post("maps/api/place/add/json")
.then()
.statusCode(200)
.body("scope", equalTo("APP"))
.header("server", "Apache/2.4.52 (Ubuntu)")
.extract()
.response().asString();
System.out.println("response: " + response);
}
// 4) Post request body using using external json file
@Test
public void testPostUsingExternalJsonFile() throws FileNotFoundException {
RestAssured.baseURI = "https://rahulshettyacademy.com";
FileReader fr = new FileReader(new File(".//place.json"));
JSONTokener jt = new JSONTokener(fr);
JSONObject data = new JSONObject(jt);
System.out.println("data: " + data.toString());
String response =
given()
.log().all()
.queryParam("key", "qaclick123")
.header("Content-Type", "application/json")
.contentType("application/json")
.body(data.toString())
.when()
.post("maps/api/place/add/json")
.then().statusCode(200)
.body("scope", equalTo("APP"))
.header("server", "Apache/2.4.52 (Ubuntu)")
.extract()
.response().asString();
System.out.println("response: " + response);
}
}
Place.java
package day2.pojo;
import java.util.Arrays;
import java.util.HashMap;
public class Place {
HashMap<String, String> location;
int accuracy;
String name;
String phone_number;
String address;
String[] types;
String website;
String language;
public HashMap<String, String> getLocation() {
return location;
}
public void setLocation(HashMap<String, String> location) {
this.location = location;
}
public int getAccuracy() {
return accuracy;
}
public void setAccuracy(int accuracy) {
this.accuracy = accuracy;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String[] getTypes() {
return types;
}
public void setTypes(String[] types) {
this.types = types;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
@Override
public String toString() {
return "Place [location=" + location + ", accuracy=" + accuracy + ", name=" + name + ", phone_number="
+ phone_number + ", address=" + address + ", types=" + Arrays.toString(types) + ", website=" + website
+ ", language=" + language + "]";
}
}
Json File
{
"location": {
"lat": -38.383494,
"lng": 33.427362
},
"accuracy": 50,
"name": "Frontline house",
"phone_number": "(+91) 983 893 3937",
"address": "29, side layout, cohen 09",
"types": [
"shoe park",
"shop"
],
"website": "http://google.com",
"language": "French-IN"
}
Session 3 - Path and Query Parameter, Cookies, Headers, logs, read values from properties files
Path and Query Parameter
https://reqres.in/api/users?page=2
here
https://reqres.in/api/ Domain
users Path
page=2 parameter
package day3;
import static io.restassured.RestAssured.*;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
public class PathAndQueryParameters {
@Test
public void testQueryAndPathParameters()
{
RestAssured.baseURI = "https://reqres.in";
//https://reqres.in/api/users?page=2&id=5
given()
.pathParam("mypath", "users") //path parameter
.queryParam("page", 2) //query parameter
.queryParam("id", 5) //query parameter
.when()
.get("/api/{mypath}")
.then()
.statusCode(200)
.log().all();
}
}
Get Cookies Demo program
package day3;
import static io.restassured.RestAssured.*;
import static io.restassured.matcher.RestAssuredMatchers.*;
import static org.hamcrest.Matchers.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.testng.annotations.Test;
import api.endpoints.UserEndPoint;
import io.restassured.response.Response;
public class CookiesDemo {
public Logger logger= LogManager.getLogger(this.getClass());
@Test
public void testCookies()
{
String geturl = "https://www.google.com";
logger.info("getting cookes from google.com");
given()
.when().get(geturl)
.then()
.cookie("AEC", "AVYB7co-s8cFbPF7m504V84fGzqmyDyf3judwNLRSbPIvipOjyMLCdO9cg")
.log().all();
logger.info("cookies collected");
}
@Test
public void getCookiesInfo()
{
String geturl = UserEndPoint.getUrl().getString("googleurl");
Response response = given()
.when()
.get(geturl);
//get single cookie info
String cookieValue = response.getCookie("AEC");
System.out.println("AEC: "+ cookieValue);
//get all cookies info
Map<String, String> cookies = response.getCookies();
for(Entry entry : cookies.entrySet()) {
System.out.println(entry.getKey()+" : "+entry.getValue());
}
logger.info("cookies collected in method 2");
}
}
Get headers
package day3;
import static io.restassured.RestAssured.*;
import org.testng.annotations.Test;
import io.restassured.http.Header;
import io.restassured.http.Headers;
import io.restassured.response.Response;
public class HeadersDemo {
//@Test(priority = 1)
public void testHeaders() {
baseURI = "https://www.google.com/";
given()
.when()
.get()
.then()
.header("Content-Type", "text/html; charset=ISO-8859-1")
.and()
.header("Content-Encoding", "gzip")
.and()
.header("Server", "gws")
.log().all();
}
@Test(priority = 1)
public void getHeaders() {
baseURI = "https://www.google.com/";
Response response = given()
.when()
.get()
;
//Get single header info
String headerValue = response.getHeader("Server");
System.out.println("Header server :"+headerValue);
//get all headers
//this approach is not recommended as log().all() print all headers in the response
Headers headers= response.getHeaders();
for(Header header : headers) {
System.out.println(header.getName() +" : "+ header.getValue());
}
}
}
Logger of restassured
package day3;
import static io.restassured.RestAssured.given;
import org.testng.annotations.Test;
public class LoggingDemo {
@Test
public void testLogs() {
given()
.when()
.get("https://reqres.in/api/users?page=2")
.then()
//.log().body()
//.log().headers()
//.log().cookies()
.log().everything();
}
}
Read values from properties file
Create a properties file ie routes.properties in src/test/resources folder. provide all route url as below
googleurl=https://www.google.com
Now create a class to load and read this properties file
ie
package api.endpoints;
import java.util.ResourceBundle;
public class UserEndPoint {
//method created for getting URL's from properties file
public static ResourceBundle getUrl() {
ResourceBundle routes = ResourceBundle.getBundle("routes");//Load properties file
return routes;
}
}
user this class and get properties values
package day3;
import static io.restassured.RestAssured.given;
import org.testng.annotations.Test;
import api.endpoints.UserEndPoint;
public class PropertiesFileReader {
@Test
public void testReadUrlFromPropertyFile()
{
String geturl = UserEndPoint.getUrl().getString("googleurl");
given()
.when().get(geturl)
.then()
.cookie("AEC", "Ackid1SBDMpV34YNWmBdiKiQGDDM646yVwBpWJyFY7uNdmcHhb3-EpX_OTs")
.log().all();
}
}
Session 4 - Parsing Response Data, Serialization and deserialization, Authentication
package day4;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasXPath;
import org.json.JSONObject;
import static org.hamcrest.Matchers.*;
import org.testng.annotations.Test;
import io.restassured.response.Response;
public class ParsingJSONResponseData {
@Test(priority = 1)
void parseResponseBody() {
Response response = null;
given()
.when()
.get("https://reqres.in/api/users?page=2")
.then().log().all()
.body("page", equalTo(2))
.body("per_page", equalTo(6))
.body("total", equalTo(12))
.body("data[0].id", equalTo(7))
.body("data[0].email", equalTo("michael.lawson@reqres.in"))
.body("data[0].first_name", equalTo("Michael"));
}
@Test(priority = 1)
void parseResponseJson() {
String json = given()
.when()
.get("https://reqres.in/api/users?page=2").asString();
System.out.println("JSONObject: "+json);
JSONObject jsObject = new JSONObject(json);
Object data = jsObject.get("data");
System.out.println("data: "+data.toString());
}
}
File upload and download
package Day5;
import java.io.File;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class UploadFile {
@Test
public void singleFileUpload()
{
File myfile = new File("C:\\AutomationPractice\\Test1.txt");
given()
.multiPart("file",myfile)
.contentType("multipart/form-data")
.when()
.post("http://localhost:8080/uploadFile")
.then()
.statusCode(200)
.body("fileName", equalTo("Test1.txt"))
.log().all();
}
@Test
public void multipleFileUpload()
{
File myfile1 = new File("C:\\AutomationPractice\\Test1.txt");
File myfile2 = new File("C:\\AutomationPractice\\Test2.txt");
given()
.multiPart("files",myfile1)
.multiPart("files",myfile2)
.contentType("multipart/form-data")
.when()
.post("http://localhost:8080/uploadMultipleFiles")
.then()
.statusCode(200)
.body("[0].fileName", equalTo("Test1.txt"))
.body("[1].fileName", equalTo("Test2.txt"))
.log().all();
}
@Test
public void multipleFileUpload1()//not work for all kind of api
{
File myfile1 = new File("C:\\AutomationPractice\\Test1.txt");
File myfile2 = new File("C:\\AutomationPractice\\Test2.txt");
File fileArr[] = {myfile1, myfile2};
given()
.multiPart("files",fileArr)
.contentType("multipart/form-data")
.when()
.post("http://localhost:8080/uploadMultipleFiles")
.then()
.statusCode(200)
.body("[0].fileName", equalTo("Test1.txt"))
.body("[1].fileName", equalTo("Test2.txt"))
.log().all();
}
@Test
void fileDownload() {
given()
.when()
.get("http://localhost:8080/downloadFile/Test1.txt")
.then()
.statusCode(200)
.log().body();
}
}
Serialization and deserialization
package day6;
import java.util.HashMap;
import org.testng.annotations.Test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import day2.pojo.Place;
//Pojo ----> JSON Object ----> Pojo
public class SerializationDeserialization {
//@Test
public void convertPojoToJson() throws JsonProcessingException
{
//created java object using pojo class
Place data = new Place();
HashMap<String, String> location = new HashMap<String, String>();
location.put("lat", "-38.383494");
location.put("lng", "33.427362");
data.setLocation(location);
data.setAccuracy(50);
data.setName("Frontline House");
data.setPhone_number("(+91) 987 654 3210");
data.setAddress("29, side layout, cohen 09");
String types[] = { "shoe park", "shop", "sandles" };
data.setTypes(types);
data.setWebsite("https://google.com");
data.setLanguage("French-IN");
//convert java object -->json object
ObjectMapper objMapper = new ObjectMapper();
String jsonData = objMapper.writerWithDefaultPrettyPrinter().writeValueAsString(data);
System.out.println(jsonData);
}
@Test
public void convertJsonToPojo() throws JsonProcessingException
{
String jsondata = "{\r\n"
+ " \"location\" : {\r\n"
+ " \"lng\" : \"33.427362\",\r\n"
+ " \"lat\" : \"-38.383494\"\r\n"
+ " },\r\n"
+ " \"accuracy\" : 50,\r\n"
+ " \"name\" : \"Frontline House\",\r\n"
+ " \"phone_number\" : \"(+91) 987 654 3210\",\r\n"
+ " \"address\" : \"29, side layout, cohen 09\",\r\n"
+ " \"types\" : [ \"shoe park\", \"shop\", \"sandles\" ],\r\n"
+ " \"website\" : \"https://google.com\",\r\n"
+ " \"language\" : \"French-IN\"\r\n"
+ "}";
ObjectMapper objMapper = new ObjectMapper();
Place place = objMapper.readValue(jsondata, Place.class);
System.out.println(place.getAddress());
}
}
Authentication
package day7;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class Authentication {
//@Test
public void testBasicAuthentication() {
given()
.auth().basic("postman", "password")
.when()
.get("https://postman-echo.com/basic-auth")
.then()
.statusCode(200)
.body("authenticated", equalTo(true))
.log().all();
}
//@Test
public void testDigestAuthentication() {
given()
.auth().digest("postman", "password")
.when()
.get("https://postman-echo.com/basic-auth")
.then()
.statusCode(200)
.body("authenticated", equalTo(true))
.log().all();
}
//@Test
public void testPreemptiveAuthentication() {
given()
.auth().preemptive().basic("postman", "password")
.when()
.get("https://postman-echo.com/basic-auth")
.then()
.statusCode(200)
.body("authenticated", equalTo(true))
.log().all();
}
//@Test
void testBearerTokenAuthentication()
{
String bearerToken = "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";
given()
.headers("Authorization", "Bearer "+ bearerToken)
.when()
.get("https://api.github.com/user/repos")
.then()
.statusCode(200)
.log().all();
}
//@Test
void testOAuth1Authentication() {
given()
.auth().oauth("consumerKey", "consumerSecret", "accessToken", "tokenSecret")
.when()
.get("url")
.then()
.statusCode(200)
.log().all();
}
//@Test
void testOAuth2Authentication() {
given()
.auth().oauth2("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")
.when()
.get("https://api.github.com/user/repos")
.then()
.statusCode(200)
.log().all();
}
@Test
void testApiKeyAuthentication() {
given()
.queryParam("appid", "55e70390cce0987757f9cc1f09e40d71")
.when()
.get("http://api.openweathermap.org/data/2.5/air_pollution?lat=50&lon=50")
.then()
.statusCode(200)
.log().all();
}
}
Pom.xml i used for all above examples
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>RestAssuredTraining</groupId>
<artifactId>RestAssuredTraining</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<pluginManagement>
<plugins>
<!-- this required to run our app from command prompt of
jenkins-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.3</version>
<configuration>
<!-- put your configurations here -->
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.12.1</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<dependencies>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.3.2</version>
<scope>test</scope>
</dependency>
<!-- json-path is included default if you are importing rest-assured dependency -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>5.3.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>5.3.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.7.0</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20230227</version>
</dependency>
<!--
https://mvnrepository.com/artifact/com.github.scribejava/scribejava-apis -->
<dependency>
<groupId>com.github.scribejava</groupId>
<artifactId>scribejava-apis</artifactId>
<version>5.3.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.github.javafaker</groupId>
<artifactId>javafaker</artifactId>
<version>1.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.aventstack/extentreports -->
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>5.0.9</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
</project>
references https://github.com/rest-assured/rest-assured/wiki/Usage#example-1---json
This content originally appeared on DEV Community and was authored by Brijendra Rai
Brijendra Rai | Sciencx (2024-08-25T01:08:21+00:00) RestAssured RestAPI automation testing Crash Course. Retrieved from https://www.scien.cx/2024/08/25/restassured-restapi-automation-testing-crash-course/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.