“Mirror mirror on the wall, who is the best API of them all”.
We hardly have any memory left of the time when we didn’t use Rest APIs for development of Web and Mobile applications. They have indeed helped reduce cohesion and scale up our applications massively. While we keep creating Rest APIs one after the other, someone has to do the dirty job of ensuring that these APIs function correctly and remain healthy. This is where API testing comes in, and one of the most popular tools for this purpose is REST Assured. In this blog, we’ll dive deep into REST Assured for API Testing, exploring its features, advantages, and how to use it.
What is REST Assured?
REST Assured is a powerful Java-based library used for testing and validating RESTful web services. It simplifies the process of testing APIs by providing a domain-specific language (DSL) that makes it easy to write readable and maintainable tests. REST Assured is built on top of other popular Java libraries like Apache HTTP Client, Hamcrest, and JsonPath, which enhances its capabilities for making HTTP requests and validating responses.
Now what is a domain specific language, you may ask. It is a programming language with higher level of abstraction optimized to solve a specific class of problems.(Too many jargons!). In simple words, a DSL has highly specific syntaxes that makes it easy to develop solutions for a particular problem.
As far as Rest Assured is concerned, it was invented to test APIs. It provides syntaxes specifically to develop Automated API test scripts quickly and efficiently.
Key Features of REST Assured
1. Ease of Use: REST Assured’s syntax is designed to be intuitive and easy to understand. This allows testers and developers to write tests quickly and efficiently.
2. Integration with Testing Frameworks: REST Assured integrates seamlessly with popular testing frameworks like JUnit and TestNG, enabling you to include API tests as part of your test suite.
3. Support for Various HTTP Methods: REST Assured supports all HTTP methods, including GET, POST, PUT, DELETE, PATCH, and OPTIONS.
4. Request and Response Specification: You can define specifications for requests and responses, which can be reused across multiple tests, making your code more maintainable.
5. Authentication and Authorization: REST Assured supports various authentication mechanisms, including Basic Auth, OAuth, and API tokens.
6. Validation and Assertion: With built-in support for Hamcrest matchers, REST Assured makes it easy to validate and assert the contents of API responses.
Setting Up REST Assured
Before we start writing tests with REST Assured, we need to set up our project. Here’s a step-by-step guide to getting started with REST Assured in a Maven project.
Maven is a build automation and project management tool for java-based projects. So why are we using maven?
The answer is very simple. Imagine you are developing an application. You are using some existing Java libraries to develop the features of your application. Once developed, we need to push our code in GitHub or any other repository. Are we going to push all the dependencies along with our code?
What if you could specify all the dependencies somewhere, and when you download the project, you can automatically download those dependencies? That’s exactly why we use Maven. Maven lets you specify the dependencies in a file called “pom.xml” file. Maven provides you with commands to download the dependencies. It also does many awesome stuffs. Learn more about maven from here.
Step 1: Create a Maven Project
If you don’t already have a Maven project, you can create one using your favorite IDE or from the command line.
mvn archetype:generate -DgroupId=com.example -DartifactId=rest-assured-demo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
cd rest-assured-demo
Step 2: Add REST Assured Dependency
In your `pom.xml` file, add the following dependency for REST Assured:
<dependencies>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.0.1</version>
<scope>test</scope>
</dependency>
<!-- Add other dependencies like JUnit or TestNG if needed -->
</dependencies>
Step 3: Write Your First Test
Now, let’s write a simple test to verify that our setup is working. We’ll use a public API (https://jsonplaceholder.typicode.com) for this example.
import io.restassured.RestAssured;
import org.junit.Test;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class ApiTest {
@Test
public void testGetPosts() {
given()
.baseUri("https://jsonplaceholder.typicode.com")
.when()
.get("/posts")
.then()
.statusCode(200)
.body("size()", greaterThan(0));
}
}
In this test, we are making a GET request to the `/posts` endpoint and verifying that the response status code is 200 and that the response body contains more than 0 items.
Advanced Usage of REST Assured
Request Specifications
To avoid repetition in your tests, you can define request specifications that can be reused across multiple tests. For example:
import io.restassured.specification.RequestSpecification;
import static io.restassured.RestAssured.*;
public class ApiTest {
private RequestSpecification requestSpec;
@Before
public void setUp() {
requestSpec = given()
.baseUri("https://jsonplaceholder.typicode.com")
.header("Content-Type", "application/json");
}
@Test
public void testGetPosts() {
given()
.spec(requestSpec)
.when()
.get("/posts")
.then()
.statusCode(200)
.body("size()", greaterThan(0));
}
}
Response Specifications
Similar to request specifications, you can define response specifications to reuse validation logic:
import io.restassured.specification.ResponseSpecification;
import static io.restassured.RestAssured.*;
public class ApiTest {
private RequestSpecification requestSpec;
private ResponseSpecification responseSpec;
@Before
public void setUp() {
requestSpec = given()
.baseUri("https://jsonplaceholder.typicode.com")
.header("Content-Type", "application/json");
responseSpec = expect()
.statusCode(200)
.contentType("application/json");
}
@Test
public void testGetPosts() {
given()
.spec(requestSpec)
.when()
.get("/posts")
.then()
.spec(responseSpec)
.body("size()", greaterThan(0));
}
}
Handling Authentication
REST Assured makes it easy to handle different authentication mechanisms. Here are a few examples:
#### Basic Authentication
@Test
public void testBasicAuth() {
given()
.auth().basic("username", "password")
.baseUri("https://api.example.com")
.when()
.get("/secure-endpoint")
.then()
.statusCode(200);
}
#### OAuth 2.0
@Test
public void testOAuth2() {
given()
.auth().oauth2("your_access_token")
.baseUri("https://api.example.com")
.when()
.get("/secure-endpoint")
.then()
.statusCode(200);
}
Data-Driven Testing
You can use data providers to run the same test with different sets of data. Here’s an example using TestNG’s `@DataProvider`:
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class ApiTest {
@DataProvider(name = "userIds")
public Object[][] createUserIds() {
return new Object[][] {
{ 1 }, { 2 }, { 3 }
};
}
@Test(dataProvider = "userIds")
public void testGetUserById(int userId) {
given()
.baseUri("https://jsonplaceholder.typicode.com")
.when()
.get("/users/" + userId)
.then()
.statusCode(200)
.body("id", equalTo(userId));
}
}
Best Practices for Using REST Assured
1. Keep Tests Isolated: Ensure that each test is independent and doesn’t rely on the state left by previous tests.
2. Use Assertions Wisely: Avoid over-asserting in your tests. Focus on the key elements that need validation.
3. Leverage Specifications: Use request and response specifications to avoid code duplication and make your tests more maintainable.
4. Mock External Services: When testing your application, mock external dependencies to avoid flakiness and ensure consistent test results.
5. Integrate with CI/CD: Include your REST Assured tests in your Continuous Integration and Continuous Deployment pipelines to catch issues early.
Conclusion
REST Assured is a powerful and versatile tool for API testing, offering a range of features that make it easy to write, maintain, and execute tests. Its intuitive syntax and integration with popular testing frameworks make it a favorite among testers and developers alike. By following best practices and leveraging advanced features like request and response specifications, authentication handling, and data-driven testing, you can ensure that your API tests are robust, reliable, and efficient.
Whether you’re just getting started with API testing or looking to enhance your existing test suite, REST Assured is a tool worth considering. Happy testing!