Automate API Testing With Java And Rest Assured

Darmawan Hadiprasetyo
4 min readMar 17, 2023

--

API automation testing is an important aspect of software testing, as APIs are the backbone of modern web applications. In this article, we will explore how to automate API testing using Rest Assured, a popular Java-based library for testing RESTful APIs.

What is Rest Assured?

Rest Assured is a Java-based library for testing RESTful APIs. It provides a simple and intuitive DSL (Domain-Specific Language) for writing test cases, which makes it easy for developers to write and maintain automated tests. Rest Assured supports various HTTP methods such as GET, POST, PUT, DELETE, PATCH, and more, and can be easily integrated with popular testing frameworks like TestNG and JUnit.

Setup Rest Assured

Add Rest Assured dependency to your Maven/Gradle configuration. (Click here).

<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>x.x.x</version>
<scope>test</scope>
</dependency>
testImplementation 'io.rest-assured:rest-assured:x.x.x'

Rest Assured Structure

Thinking about Rest Assured, I think it’s pretty similar to Gherkin syntax. Where Rest Assured is divided into 3 main parts:

  1. Given
  • “Given” is a pre-condition for your API testing where you set up everything that’s needed for the test, like the base URL, any request headers or parameters, or any preconditions that need to be met. It’s like getting everything ready before you start.
  • Here are the things you can setup in “Given”: Base URL, request headers, request parameters and request body.

2. When

  • “When” is where you actually send the HTTP request to the server and get a response back. You also define the request method like GET, POST, PUT, etc in “When”.

3. Then

  • “Then” is where you check the response that you got from the server and make sure it’s what you expected. This is where you’ll check things like the status code, response body, headers, or anything else that’s important for your test.

Logic example:

  • Given that I have set up my base URL and any necessary headers or parameters, When I send an HTTP request to the server, Then I should receive a response that matches what I expected based on the request.

Let’s Code

Before we start, let’s take a look at this postman example:

  1. Parameters

2. Headers

3. Request Body

So, basically everything you put as URL, Parameters, Headers and Body is included in Given condition. And your request method such as GET, POST, PUT, etc is included in When condition.

When we translate it into our Rest Assured code, then it will look like this:

import io.restassured.builder.RequestSpecBuilder;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.lessThan;

public class TestRestAssured {
@Test
public void testMyApi() {
String jsonBody = "{\"email\":\"dhadiprasetyo@gmail.com\",\"uid\":\"Jzr0sOORprar10kay6CweZ5FNYP2\"}";

Response response = given().baseUri("http://127.0.0.1:8000")
.queryParam("version", "1.0")
.header("Authorization", "yourauthhere")
.header("Signature", "yoursignaturehere")
.body(jsonBody)
.when().post("/getuserdata/")
.then().assertThat().statusCode(200)
.header("Content-Type", "application/json")
.header("Cache-Control", "max-age=3600")
.body("name", equalTo("Darmawan Hadiprasetyo"))
.time(lessThan(5000L))
.extract().response();
}
}

Let’s deep dive into that code:

  1. First we are setting up the pre-condition in given()
given().baseUri("http://127.0.0.1:8000")
.queryParam("version", "1.0")
.header("Authorization", "yourauthhere")
.header("Signature", "yoursignaturehere")
.body(jsonBody)

2. Then define the request method in when() which is POST in this example

.when().post("/getuserdata/")

3. Then we are asserting the status code, header, body and response time from our request

.then().assertThat().statusCode(200)
.header("Content-Type", "application/json")
.header("Cache-Control", "max-age=3600")
.body("name", equalTo("Darmawan Hadiprasetyo"))
.time(lessThan(5000L))
.extract().response();

How to extract the response body:

For example this will be our response from our previous request:

{
"name": "Darmawan Hadiprasetyo",
"linkedin": "https://www.linkedin.com/in/darmawanhadip/"
"role": "SDET"
}

Here’s how we can extract those datas:

JsonPath responseBody = response.jsonPath();
String fullName = responseBody.getString("name");
String linkedIn = responseBody.getString("linkedin");
String role = responseBody.getString("role");

Bonus — RequestSpecification

In most cases, you will have to test many APIs but with the same pre-condition such as BaseURL, parameters and headers. To remove redundancy in our code, we could use RequestSpecification as our spec builder and reuse it in our other tests as follows:

import io.restassured.builder.RequestSpecBuilder;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.lessThan;

public class TestRestAssured {
public static RequestSpecification requestSpecification() {
return new RequestSpecBuilder().setBaseUri("http://127.0.0.1:8000")
.addQueryParam("version", "1.0")
.addHeader("Authorization", "yourauthhere")
.addHeader("Signature", "yoursignaturehere")
.build();
}

@Test
public void testMyApi() {
String jsonBody = "{\"email\":\"dhadiprasetyo@gmail.com\",\"uid\":\"Jzr0sOORprar10kay6CweZ5FNYP2\"}";

Response response = given().spec(requestSpecification())
.body(jsonBody)
.when().post("/getuserdata/")
.then().assertThat().statusCode(200)
.header("Content-Type", "application/json")
.header("Cache-Control", "max-age=3600")
.body("name", equalTo("Darmawan Hadiprasetyo"))
.time(lessThan(5000L))
.extract().response();

JsonPath responseBody = response.jsonPath();
String fullName = responseBody.getString("name");
String linkedIn = responseBody.getString("linkedin");
String role = responseBody.getString("role");
}
}

Now you can reuse requestSpecification() method in any other tests you need with the same pre-conditions. See the difference with our previous code:

// previous
Response response = given().baseUri("http://127.0.0.1:8000")
.queryParam("version", "1.0")
.header("Authorization", "yourauthhere")
.header("Signature", "yoursignaturehere")
.body(jsonBody)
.when().post("/getuserdata/")

// then
Response response = given().spec(requestSpecification())
.body(jsonBody)
.when().post("/getuserdata/")

Our code is now much simpler by using given().spec().

Conclusion

Rest Assured is a powerful Java-based library for automating API testing. It provides an intuitive DSL for writing test cases, supports a wide range of HTTP methods and assertions, and can be easily integrated with popular testing frameworks like TestNG and JUnit. By following the steps outlined in this article, you can easily write and maintain automated API tests using Rest Assured.

Thank you for learning with me. If you have any feedback or questions feel free to contact me thru:

--

--