An Introduction to Testing APIs Using REST Assured

API connected to various devices

In this post, I will introduce you to the basics of API and REST Assured library, provide you with a few samples on how to start off when making test cases in REST Assured, as well as show some alternative tools and explain how they differ.

Requirements

To start using Rest Assured, you will need to add REST Assured dependencies to your project, depending on if you are using Gradle or Maven with your project.

Gradle:

testCompile "io.rest-assured:rest-assured:3.1.0"

Maven:

<dependency>
   <groupId>io.rest-assured</groupId>
   <artifactId>rest-assured</artifactId>
   <version>3.1.0</version>
   <scope>test</scope>
</dependency>

Additionally, you will need to add static imports to get added functionality, that will come in handy when writing API tests. For example, I use Java Hamcrest for assertThat(a, equalTo(b)) statement that can help me understand wether response data returned from server equals to expected data.

import static io.restassured.RestAssured.*;
import static org.hamcrest.*;

What is API

API or “Application Programming Interface” is an interface between two software systems, which provides interaction and data sharing. The basic principle of API is to send requests to a server and receive a response, indicating to the sender whether the request was successful or not. For example, if there are endpoints which are responsible for a store’s shopping cart and the ability to populate and empty it, a request to add to the composition of the basket is sent, which in turn returns either a positive or a negative response – whether the request was successful or not. Likewise it is possible to make a request in which the contents of the basket are removed from it, therefore, the user has performed the basic function of the shopping cart within seconds and checked its ability to work without going through the UI.

Response codes

As mentioned above, in the case of a request, a reply from the server is received in the form of a response code, which gives an indication on the type of response that it is. In general, there are more than 60 possible response codes, but some of them are more common that others, for example:

200 OK
201 Created
204 No Content
304 Not Modified
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
500 Internal Server Error

These response codes are designed so that the first number of each code corresponds to a certain informative group, which reflects the type of response it has.

Code class

Meaning

1xx

Informational

2xx

Success

3xx

Redirection

4xx

Client error

5xx

Server error

API call methods

API call methods define what type of a request will be sent. Whether for it to be a new addition of data to a platform, or an update to already existing data. Just like with response codes, there’s a multitude of call methods, with the most popular being:

  • GET method in API tests is probably the most commonly used, because it obtains information from the corresponding endpoint without requiring input data. This method can receive just a response code, or a response code and response body, containing data that was asked to be returned.
  • POST method is used to send new information to the server, or to update already existing information, by entering the requested information in the request body before sending it. Most often, this method is used to create new entries in an existing database.
  • PUT method is used only to update existing data and returns a positive result only if the system contains already existing and updatable data.
  • PATCH method is similar to PUT, in that it is used for updating existing data, but differs from it in so that to use it, it does not necessarily indicate that the user has to input all data of the database record. It is enough to specify the desired data which needs to be updated.
  • DELETE method is self-explanatory. It’s used to delete existing data from the system. This option is non-reversible.

When is API testing useful

One of the API’s advantages is that testing can start even before the creation of a UI, allowing for early testing, as the tester does not have to wait until the programmer creates UI elements for each functionality. API tests both manually and automated run much faster because the tester physically does not need to go through the UI, repost test data. All it takes is a single, or multiple, API calls to be performed to successfully test functionality.

What is REST

REST or “Representational State Transfer” is a type of architecture created as a guideline for computer systems. It determines things like customer-server relationships, but does not save client contexts on a server between requests so that the client can communicate with the server without knowing previous requests, unified guidelines, etc. Most commonly used for HTTP.

What is REST Assured

REST Assured is a Java language library for testing and validating REST web services, based on HTTP. This DSL or “Domain-Specific Language” went into development in 2010. Unlike other competitors, REST Assured is open source, which makes it easily accessible to everyone, therefore, becoming one of the most popular REST API validation tools. This library has been developed by Jayway.

The level of complexity is determined by the user when creating test cases using REST Assured. Here are a few simple examples of basic calls using some of the most popular methods, starting with GET.

public void getRequest() {
   given()
       .when().get(environment + "/store/inventory")
       .then().assertThat().statusCode(200);
}

The call consists of a “header”, which indicates the called methods “Content-Type”, followed by the indication that the method used is a GET method, followed by the address of the endpoints and the condition of what result is expected, which in this case is the response code of 200, meaning that the test should pass. If the GET method receives an answer that holds a response body, there is an option to also add that as an expectation.

A bit more complex request is a POST request, which includes everything the GET method has, as well as a body containing input data.

public void postRequest() throws Exception {
   given()
       .body("{ \"id\": " + inputId + ", \"quantity\": 1}")
       .header("Content-Type", "application/json")
       .when().post(environment + "/store/order")
       .then().assertThat().statusCode(200);
}

Let’s take a look at the DELETE method, where a common practise is the requirement of dynamic data as part of the endpoint link. Usually it is the ID of an existing data previously posted, noted as “inputId” in this example, which was previously used to POST a new entry.

public void deleteRequest() {
   given()
       .when().delete(environment + "/store/order/" + inputId)
       .then().log().ifError()
       .assertThat().statusCode(200);
}

REST Assured vs Apimation

We at TestDevLab are working with various API testing tools on a daily basis and have vast experience with them. We know which tool is best used in certain scenarios and we are developing our own tools. One of these tools is called Apimation, and, just like Rest Assured, it is made for testing API. Aside from similar features that both share, such as support for a CLI client, integrate with CI, pre-defined functionality for methods, etc., each have their pros and cons, which are listed below.

Apimation

Pros

  • Friendlier to beginners and people who are new to programming.
  • Supports parallel test case run execution, as well as multithreaded test step loops.
  • All functional scenarios can be reused to perform load and stress testing.
  • Option to create test sets, based on functionality and level of severity.
  • Import test step definitions from Swagger 2.0 and OpenAPI 3.0 documentation to automatically keep all test scenarios up to date.
  • No need for test code maintenance, because all test scenarios and definitions are written in YAML.
  • Ability to combine all other command line tool executions and unit tests into test scenarios with additional assertions and data extractions between system command steps.

Cons

  • Test environment machines must have an outgoing connection to the Internet to be able to execute any of the test scenarios.
  • For some custom and unusual test scenarios built-in Javascript engine feature has to be used, no other languages supported yet.
  • Not an open source tool, though customer support will be available for upcoming community version.

Rest Assured

Pros

  • More flexibility with writing tests, as it is based on Java.
  • Is open source and free to use for everyone.
  • Can be used with any open source reporting tool.
  • Easy to integrate with JUnit and TestNG frameworks, for greater added functionality.
  • Supports Given/When/Then notation, making the code easier to read.
  • Supports multiple authentication methods, including OAuth1, OAuth2 and Form authentication.
  • Support for Proxy configuration.

Cons

  • Requires knowledge of the Java programming language
  • The user has to write code for every test case
  • Performance testing is not integrated in this tool
  • Not beginner friendly

Summary

API testing is yet another way to test your project. It provides additional advantages, such as speedy test execution, or the ability to test even before the UI has been created. In this blog post we learned the basic principles of what an API is, what is it’s purpose, and how to use it to create simple requests using REST Assured, and some of the pros and cons of using it. That being said, this blog post just delved into the world of API testing and REST Assured as a testing tool, but it should cover the basics of what is possible to achieve with the tools given, and maybe spark an interest to those who have yet to consider API as a future tool for testing.

Subscribe to our newsletter

Sign up for our newsletter to get regular updates and insights into our solutions and technologies: