Testing REST endpoints using REST Assured

RESTfil-API

     REST Assured is a Java library that provides a domain-specific language for writing powerful, maintainable tests for RESTful APIs. REST Assured supports the familiar Given/When/Then syntax from behavior-driven development (BDD), resulting in a test that is easy to read and takes care of everything with just a single line of code. Here I would like to explain commonly using GET, POST, DELETE actions with examples. Along with this I would like to explain how verification happening with each test.

Prerequisites

  1. Create Maven project.
  2. Add dependencies like rest-assured, hamcrest-all and testng.
  3. Import following packages:
    1. import staticrestassured.RestAssured.*;
    2. import static org.hamcrest.Matchers.*;

Important Actions or Operations:

  1. makeSureThatApiIsUp() – To make sure that API is up and running

@Test(description = “To make sure that API is up”)
public void makeSureThatApiIsUp() {
given().when().get(“http://restapi.demoqa.com/utilities/weather/city/Hyderabad”).then().assertThat().statusCode(200);
}

  1. verifyDataInResponseBody() – To verify the given data belongs to the response body of the API

@Test(description = “To verify that given data belongs to the response body”)
public void verifyDataInResponseBody() {
given().when().get(“http://restapi.demoqa.com/utilities/weather/city/Cochin”).then().body(containsString(“Hyderbad”));
}

  1. verifyMultipleDataInResponseBody() – To verify that multiple values belongs to the response body of the API

@Test(description = “To verify that multiple values belongs to the response body”)
public void verifyMultipleDataInResponseBody() {
given().when().get(“http://restapi.demoqa.com/utilities/weather/city/Cochin”).then().body(“City”, equalTo(“Cochin”)).body(“WindSpeed”, equalTo(“7.2 Km per hour”));
}

  1. verifySingleSpecificDataInResponseBody() – To verify the specific value belongs to the response body of the API

@Test(description = “To verify that specific value belongs to the response body”)
public void verifySingleSpecificDataInResponseBody() {
given().when().get(“http://restapi.demoqa.com/utilities/weather/city/Cochin”).then().body(“City”,equalTo(“Cochin”));
}

  1. verifyContentType() – To verify the content type

@Test(description = “To verify the content type”)
public void verifyContentType() {        given().when().get(“http://restapi.demoqa.com/utilities/weather/city/Cochin”).then().assertThat().statusCode(200).and().contentType(“application/json”);
}

  1. verifyContentTypeAndHeaderValue() – To verify the content type and the header values

@Test(description = “To verify the content type and header values”)
public void verifyContentTypeAndHeaderValue() {
given().when().get(“http://restapi.demoqa.com/utilities/weather/city/Cochin”).then().assertThat().statusCode(200).and().contentType(“application/json”).and().header(“Content-Length”, equalTo(“158”));
}

  1. verifyHeaderValue() – To verify the header values

@Test(description = “To verify the header value”)
public void verifyHeaderValue() {
given().when().get(“http://restapi.demoqa.com/utilities/weather/city/Cochin”).then().assertThat().statusCode(200).and().header(“Content-Length”, equalTo(“159”));
}

  1. verifyAPIWithQueryParameter() – To verify the API request with query parameter

@Test(description = “To verify API with query parameter”)
public void verifyAPIWithQueryParameter() {
String cityname = “Cochin”;
given().param(“text”, cityname).when().get(“http://md5.jsontest.com/?text=” + cityname).then().body(containsString(“Cochin”));
}

  1. verifyAPIWithBasicAuthentication_ShouldBeGivenAccess() – To verify the basic authentication

@Test(description = “To verify basic authentication”)
public void verifyAPIWithBasicAuthentication_ShouldBeGivenAccess() {
given().auth().preemptive().basic(“username”, “password”).when().get(“https://xxxxxxxxxxxxxxxxx.com/api/auth/login/”).then().assertThat().statusCode(200);
}

  1. verifyAPIWithOAuth2Authentication_ShouldBeGivenAccess() – To verify the OAuth2 secured authentication

@Test(description = “To verify OAuth2-secured authentication”)
public void verifyAPIWithOAuth2Authentication_ShouldBeGivenAccess(){
given().auth().oauth2(“460bfecd0bbba1a0d9dfdbbbecdf1008”).when().get(“https://openweathermap.org/”).then().assertThat().statusCode(200);
}

  1. extractDataFromResponseBody() – To extract value from the response body.

@Test(description = “To extract value from Response body”)
public void extractDataFromResponseBody() {
String circuitId = given().when().get(“http://restapi.demoqa.com/utilities/weather/city/Cochin”).then().extract().path(“Temperature”);
System.out.println(circuitId);
}

  1. toDeleteData() – To delete data

@Test(description = “To delete data”)
public void toDeleteData() {
given().pathParam(“empNumber”,69).when().delete(“/emp/details/{empNumber}”).then().statusCode(200);
}

  1. toPostDate() – To post data

@Test(description = “To post data”)
public void toPostDate() {
Map<String, String> empdata = new HashMap<>();
empdata.put(“empNumber”, “69”);
empdata.put(“empName”, “sanoj”);
empdata.put(“empDesignation”, “Test Lead”);       given().contentType(“application/json”).body(empdata).when().post(“/emp/details”).then().statusCode(200);
}

  1. verifyMultipleAPIsUpAndRunning() – To verify multiple APIs up and running in a single shot execution using excel test data file

@Test(description = “To verify multiple APIs running”)
public void verifyMultipleAPIsUpAndRunning() {
ReadExcelData data = new ReadExcelData();
SoftAssert assertnow = new SoftAssert();
for (int i = 0; i < data.getAPIFromExcel(“.//APITestData.xlsx”, “APIS”, 2).size(); i++) {
System.out.println(data.getAPIFromExcel(“.//APITestData.xlsx”, “APIS”, 2).get(i).toString());
System.out.println(given().when().get(data.getAPIFromExcel(“.//APITestData.xlsx”, “APIS”, 2).get(i)).then().extract().statusCode());
assertnow.assertEquals(given().when().get(data.getAPIFromExcel(“.//APITestData.xlsx”, “APIS”, 2).get(i)).then().extract().statusCode(), 200);
}
assertnow.assertAll();
}

NOTE: getAPIFromExcel() is a user defined function to read the APIs from the excel file by passing the excel file path, sheet name and the column index.

You can do all the relevant actions from your end for your APIs. Create test suites and execute it.

make it perfect !

One thought on “Testing REST endpoints using REST Assured

  1. This is a great article, it is very helpful for the beginner stage.

    I have a question regarding reading data from excel, what exactly is ReadExcelData? Can it be imported, or is it an object of a class you yourself created? If so, can you pass the code?

    Thank you in advance, I appreciate this blog’s content and find it very useful.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s