Gatling

API Load Testing Using Gatling

Load testing is an important practice for APIs and applications that have lots of users. For load testing their APIs, developers can choose between many popular open source load testing tools. One of these is Gatling. This blog post will explain how to execute a load test with Gatling for a REST API endpoint that uses the GET method.

Usually, this blog covers load testing with Apache JMeter™. Both Gatling and JMeter are very powerful load testing tools. But one of the advantages Gatling offers Java developers, is the Scala development language for test creation, which is nicer to use in my opinion.
API testing using Gatling involves simulating HTTP requests to test the performance and behavior of APIs. Gatling’s powerful DSL (Domain-Specific Language) allows testers to create realistic scenarios that mimic how users interact with the API. Here’s a step-by-step guide to performing API testing using Gatling:

  1. Setup Gatling Project:
    • Download and install Gatling from the official website: https://gatling.io/open-source/
    • Unzip the downloaded package and set the GATLING_HOME environment variable to the Gatling installation directory.
  2. Create a Gatling Simulation:
    • In Gatling, test scenarios are defined as “simulations.” Create a new simulation file (usually with a .scala extension) in the user-files/simulations directory of your Gatling project.
  3. Import Gatling Classes and Libraries:
    • In the simulation file, import necessary Gatling classes and libraries, including those related to HTTP requests and scenarios.
  4. Define HTTP Configuration:
    • Configure the base URL and other settings for your API endpoints. Gatling allows you to set up a global HTTP configuration that applies to all requests.
  5. Define Test Scenarios:
    • Use Gatling’s DSL to define the test scenarios that will simulate API requests. You can specify HTTP methods, headers, request bodies, and other parameters as needed.
  6. Inject Virtual Users:
    • Gatling uses a concept called “virtual users” to simulate multiple concurrent users. Specify how many virtual users you want to inject into the scenario and the ramp-up period.
  7. Execute the Test:
    • Run Gatling from the command line, specifying the simulation file to execute. Gatling will start sending HTTP requests to the API and record the results.
  8. Analyze Test Results:
    • After the test completes, Gatling generates detailed HTML reports with various performance metrics, response times, and error rates. Analyze these reports to identify performance bottlenecks and other issues.

Here’s a basic example of a Gatling simulation for testing a simple GET request to an API:

import io.gatling.core.Predef._
import io.gatling.http.Predef._

class ApiSimulation extends Simulation {

  val httpConf = http.baseUrl("https://api.example.com")

  val scn = scenario("API Test Scenario")
    .exec(http("GET Request")
      .get("/endpoint")
      .check(status.is(200))
    )

  setUp(
    scn.inject(
      rampUsers(100) during (10)
    )
  ).protocols(httpConf)
}

In this example, we define an HTTP configuration with the base URL of the API. The scenario sends a GET request to the /endpoint and checks that the response status is 200. We inject 100 virtual users over 10 seconds to simulate the load.

POST Request with JSON Payload

import io.gatling.core.Predef._
import io.gatling.http.Predef._

class ApiSimulation extends Simulation {

  val httpConf = http.baseUrl("https://api.example.com")

  val scn = scenario("API Test Scenario")
    .exec(http("POST Request")
      .post("/endpoint")
      .header("Content-Type", "application/json")
      .body(StringBody("""{ "key1": "value1", "key2": "value2" }"""))
      .check(status.is(201))
    )

  setUp(
    scn.inject(
      constantUsersPerSec(10) during (10)
    )
  ).protocols(httpConf)
}

In this example, we create a scenario that sends a POST request with a JSON payload to the /endpoint. We set the Content-Type header to indicate that the request body is in JSON format. The scenario expects the response status to be 201 (Created). We inject a constant rate of 10 virtual users per second over 10 seconds.

Adding Custom Headers and Query Parameters

import io.gatling.core.Predef._
import io.gatling.http.Predef._

class ApiSimulation extends Simulation {

  val httpConf = http.baseUrl("https://api.example.com")

  val scn = scenario("API Test Scenario")
    .exec(http("GET Request with Headers and Parameters")
      .get("/endpoint")
      .queryParam("param1", "value1")
      .queryParam("param2", "value2")
      .header("Authorization", "Bearer YOUR_ACCESS_TOKEN")
      .check(status.is(200))
    )

  setUp(
    scn.inject(
      rampUsersPerSec(5) to 20 during (30)
    )
  ).protocols(httpConf)
}

In this example, we send a GET request to the /endpoint with custom query parameters and headers. We use the queryParam method to add parameters to the URL and the header method to include an Authorization token in the request. The scenario expects the response status to be 200. We ramp up the number of virtual users from 5 to 20 per second over 30 seconds.

Handling Dynamic Data from Responses

import io.gatling.core.Predef._
import io.gatling.http.Predef._

class ApiSimulation extends Simulation {

  val httpConf = http.baseUrl("https://api.example.com")

  val scn = scenario("API Test Scenario")
    .exec(http("GET Request with Dynamic Data")
      .get("/data")
      .check(jsonPath("$.id").saveAs("itemId"))
      .check(status.is(200))
    )
    .exec(http("GET Request with Dynamic URL")
      .get("/items/${itemId}")
      .check(status.is(200))
    )

  setUp(
    scn.inject(
      constantUsersPerSec(10) during (20)
    )
  ).protocols(httpConf)
}

In this example, we send a GET request to the /data endpoint and extract the value of the id field from the JSON response using Gatling’s jsonPath function. We save this value as a session variable named itemId. Then, we use this dynamic value to construct a new URL and send another GET request to /items/${itemId}. The scenario expects both responses to have a status of 200. We inject a constant rate of 10 virtual users per second over 20 seconds.

Leave a Reply