How To Do API Load Testing With Gatling

APIs are the foundation of every software. Conducting API Load Testing is a great way to minimize performance risks and obtain useful feedback for an application by ensuring that an API can handle an expected load to increase its scalability and performance. Gatling is a handy tool to conduct stress tests, capacity tests, and performance tests.

What Is A Performance Test?

Performance testing is generally a testing practice performed to determine a system’s performance in terms of responsiveness and stability under a particular workload. It helps in planning if the system needs to be scaled if the load increases and how much load a system can handle.

Gatling Test Structure

Every Gatling script must have 3 essential parts.

1)Protocol: In the HTTP protocol, we need to define the base URL that we want to test and other resource configurations as per the scenario.

2)Scenario: In the Simulation class, we can have numerous scenarios which contain different HTTP methods like GET/POST/DELETE calls.

3)Setup: Where we can add the simulation strategy.setUp() is the Gatling simulation base method. The setUp() call the scenario object and passes the number of users using different injection profiles.

The test class should stretch out the fundamental Simulation class to run the test.

Gatling Test Structure

What We Will Test

We will be testing a sample API for demo purposes. We will perform CRUD operations to check the Gatling tool’s capability to handle user load.

URL: https://reqres.in/

1)Open IntelliJ

2)Navigate to the project structure

3)Create a new Package “API_Tests”

4)Create a Java Class that extends the Simulation class

Implement API Load Testing

1)Import Required Gatling Libraries

Add below mentioned static imports to your class.

import static io.gatling.javaapi.core.CoreDsl.*;
import static io.gatling.javaapi.http.HttpDsl.http;

2)Define the protocol

private HttpProtocolBuilder httpProtocol = http.baseUrl("https://reqres.in/api");

3)Define the Scenario

3.1)Fetch User Details

private ScenarioBuilder FetchUsers = scenario("Get API Request Demo").exec(
            http("Get Single User")
                  .get("/users/2")
                    .check(status().is(200)).
            check(jsonPath("$.data.first_name").is("Janet"))).pause(1);

I have built a simple scenario for the GET method. Here our aim is to fetch the first name of the user and simply assert the status code and validate that the “first_name” of the user is ‘Janet’.

3.2)Create a new User

Endpoint: /users

The goal is to create a new user with the given request payload.

Validation: Check the status code and name field

{
    "name": "QaAutomationHub",
    "job": "leader"
}
private ScenarioBuilder Createusers = scenario("Create User").exec(
            http("Create a new User")
                 .post("/users").header("content-type","application/json")
                  .asJson()
                    .body(StringBody("{\n" +
                            "    \"name\": \"QaAutomationHub\",\n" +
                           "    \"job\": \"leader\"\n" +
                            "}")).asJson()
                    .check(status().is(201),jsonPath("$.name").is("QaAutomationHub"))).pause(1);

3.3)Update Existing User

  private ScenarioBuilder Upateusers = scenario("Update User").exec(
            http("Update the User")
                   .put("/users/2").header("content-type","application/json")
                    .asJson().body(RawFileBody("Data/user.json"))
          .check(status().is(200),jsonPath("$.name").is("qaautomationhub"));
                           

3.4)Delete the User

 private ScenarioBuilder Deleteusers = scenario("Delete User").exec(
            http("Delete the User")
                .delete("/users/2").header("content-type","application/json")
                    .check(status().is(204)));

4)Simulation

{
 setUp(
      FetchUsers.injectOpen(atOnceUsers(10))).protocols(httpProtocol);
 }

simulation is the definition of a complete test with populations assigned to their scenario. It is the sum of all the scenarios configured with their own injection profile.

{
   setUp(
        Createusers.injectOpen(rampUsers(5).during(5)),
        Upateusers.injectOpen(rampUsers(10).during(7)),
        Deleteusers.injectOpen(rampUsers(10).during(7)))
                      .protocols(httpProtocol);
        FetchUsers.injectOpen(atOnceUsers(30)).protocols(httpProtocol);
}

The scenario we define is like Injecting a given number of users(30) at once while fetching user details. Ramping load simulations by injecting a given number of users distributed evenly on a time window of a given duration while creating and deleting users.

The output of the API Test

Execute the Engine class. When the load test is over, we get the global information of how our API performed on the given load scenario. It contains the min, max & mean response time, the number of requests passed/failed, and the status code of those requests.

Gatling Execution Summary
API load Testing Report

The graphs like Response time distribution & Response time percentage over time give us how our API is performing each second with the active number of users at that time.

API Load Testing Result

The code for API load testing can be found here.

Discover more from AutomationQaHub

Subscribe now to keep reading and get access to the full archive.

Continue reading