To do REST API testing using RestAssured, the very first step is to make sure that below Jar files should be imported in your Selenium test
rest-assured-4.1.2.jar
All the jars in the folder rest-assured-4.1.2-deps
If you are using Maven to handle dependencies then add the following dependency in your pom.xml file
<!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>4.1.2</version>
<scope>test</scope>
</dependency>
But as I haven't introduced maven and TestNG yet on my blog, which I will be doing very soon. So, for those who have just started learning basics of Selenium download the required JAR files and import the same in your code. Use the below URL to download the same
If you hit this URL(http://restapi.demoqa.com/utilities/weather/city/Gurgaon) in any browser then the following output you will get in JSON format.
{ "City": "Gurgaon", "Temperature": "10 Degree celsius", "Humidity": "87 Percent", "WeatherDescription": "mist", "WindSpeed": "2.6 Km per hour", "WindDirectionDegree": "330 Degree" }
So, if you get the same using RestAssured then the below code you will use, where I am fetching the weather information using GET method of Http Protocol.
import io.restassured.RestAssured;
import io.restassured.http.Method;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
public class RestTest
{
public static void main(String[] args)
{
RestAssured.baseURI="http://restapi.demoqa.com/utilities/weather/city";
RequestSpecification req=RestAssured.given();
Response res=req.request(Method.GET,"/Delhi");
String txtBody=res.getBody().asString();
System.out.println(res.getStatusLine());
System.out.println(res.headers());
System.out.println(txtBody);
}
}
I have done the following steps in the above code.
- Used the RestAssured class to generate a RequestSpecification for the URL: RestAssured.baseURI="http://restapi.demoqa.com/utilities/weather/city"; RequestSpecification req=RestAssured.given()
- Specified the HTTP Method type i.e. GET Response res=req.request(Method.GET,"/Delhi"); OR Response res=req.get("/Gurgaon");
- Sent the Request to the Server. Response res=req.request(Method.GET,"/Delhi");
- Got the Response back from the server String txtBody=res.getBody().asString();
- Printed the returned Response’s Body System.out.println(txtBody);
No comments:
Post a Comment