Rest API Automation in Java - Get Method

Using Rest-assured and TestNG


In this post, we will learn to automate REST APIs using Rest-Assured library and TestNG. Rest Assured is a Java library using which we can test and validate the REST web services. Although Rest-assured provides its own validating mechanism(assertions for validating response) but we can combine Rest-assured with TestNG to get the best of both the libraries.



During the course of this tutorial, we will be using the following-

<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>3.1.1</version>
</dependency>

  • TestNG as testing framework

Rest API Get Method Automation in Java


In the following example, we are using the Rest-assured library's "get" method to make an HTTP Get request to the restcountries.eu API- http://restcountries.eu/rest/v1/name/{countryName} that fetches the capital of a country. Then we will fetch the response in JSONArray and use TestNG's assert method for validation.


package test.qaearth;
import org.testng.Assert;
import org.testng.annotations.Test;
import io.restassured.response.Response;
import static io.restassured.RestAssured.given;
import java.util.List;
public class RestTestGet {
@Test
public void getRequestFindCapital() {
// make get request to fetch capital of norway
Response resp = given().get("http://restcountries.eu/rest/v1/name/norway");
// Fetching response in string
System.out.println(resp.asString());
// Fetching param
List alpha3Code = resp.body().path("alpha3Code");
// Asserting that capital of Norway is Oslo
Assert.assertEquals(alpha3Code.get(0), "NOR");
}
}