DEV Community

Cover image for How do you perform API testing using REST assured?
Robort
Robort

Posted on

1

How do you perform API testing using REST assured?

​API testing is a crucial aspect of modern software development, ensuring that applications communicate effectively and perform reliably. REST Assured is a powerful Java library that simplifies testing RESTful APIs, making it an essential tool for developers and testers alike. ​

Why Choose REST Assured for API Testing?

  • Comprehensive HTTP Support: REST Assured facilitates testing of various HTTP methods, including GET, POST, PUT, DELETE, OPTIONS, and HEAD.

  • Seamless Integration: It integrates smoothly with testing frameworks like JUnit and TestNG, enhancing test management and reporting.

  • Behavior-Driven Development (BDD) Syntax: Using BDD-style methods such as given(), when(), and then(), REST Assured makes test scripts more readable and maintainable.

Setting Up REST Assured for API Testing

1. Prerequisites:

  • Java Development Kit (JDK): Ensure JDK 8 or higher is installed.​
  • Integrated Development Environment (IDE): Use Eclipse, IntelliJ IDEA, or any preferred IDE.
  • Build Tool: Maven or Gradle to manage project dependencies.

2. Creating a Maven Project:

  • In your IDE, initiate a new Maven project:
  • Navigate to File > New > Project.
  • Select Maven Project and follow the prompts to set up your project structure.

3. Adding REST Assured Dependency:

  • In the pom.xml file, include the REST Assured dependency:
<dependency>
   <groupId>io.rest-assured</groupId>
   <artifactId>rest-assured</artifactId>
   <version>4.4.0</version>
   <scope>test</scope>
</dependency>
Enter fullscreen mode Exit fullscreen mode
  • For Gradle users, add the following to your build.gradle file:
testImplementation 'io.rest-assured:rest-assured:4.4.0'
Enter fullscreen mode Exit fullscreen mode

Writing Your First API Test with REST Assured

1. Import REST Assured Packages:

import io.restassured.RestAssured;
import io.restassured.response.Response;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
Enter fullscreen mode Exit fullscreen mode

2. Set Base URI:

RestAssured.baseURI = "https://reqres.in/api";
Enter fullscreen mode Exit fullscreen mode

3. Create a Test for a GET Request:

@Test
public void validateUserDetails() {
    given().
        when().
            get("/users/2").
        then().
            assertThat().
            statusCode(200).
            body("data.id", equalTo(2)).
            body("data.email", equalTo("janet.weaver@reqres.in"));
}
Enter fullscreen mode Exit fullscreen mode
  • Explanation:
  • given(): Prepares the request specification.
  • when(): Specifies the HTTP method and endpoint.
  • then(): Validates the response, checking status codes and body content.

Advanced Testing Scenarios

  • POST Request:
  @Test
  public void createUser() {
      String requestBody = "{ \"name\": \"John\", \"job\": \"tester\" }";

      given().
          header("Content-Type", "application/json").
          body(requestBody).
      when().
          post("/users").
      then().
          assertThat().
          statusCode(201).
          body("name", equalTo("John")).
          body("job", equalTo("tester"));
  }
Enter fullscreen mode Exit fullscreen mode
  • PUT Request:
  @Test
  public void updateUser() {
      String requestBody = "{ \"name\": \"Jane\", \"job\": \"developer\" }";

      given().
          header("Content-Type", "application/json").
          body(requestBody).
      when().
          put("/users/2").
      then().
          assertThat().
          statusCode(200).
          body("name", equalTo("Jane")).
          body("job", equalTo("developer"));
  }
Enter fullscreen mode Exit fullscreen mode
  • DELETE Request:
  @Test
  public void deleteUser() {
      when().
          delete("/users/2").
      then().
          assertThat().
          statusCode(204);
  }
Enter fullscreen mode Exit fullscreen mode

Best Practices for API Testing with REST Assured

  • Use Data-Driven Testing: Implement data providers to run tests with multiple data sets.​
  • Validate Response Times: Ensure APIs meet performance benchmarks by asserting response times.​
  • Handle Authentication: Incorporate necessary authentication mechanisms, such as OAuth tokens or API keys, in your tests.​
  • Integrate with CI/CD Pipelines: Automate test execution by integrating REST Assured tests into Continuous Integration and Continuous Deployment workflows.

Conclusion

REST Assured offers a robust framework for automating RESTful API tests, streamlining the validation process, and ensuring reliable application performance. By following the steps outlined above, you can effectively implement API testing in your software development lifecycle, leading to higher-quality software releases.

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 🕒

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (1)

Collapse
 
digital-manikandan profile image
Manikandan

Nice and informative article. Thanks for sharing...

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay