How to get a value from response body in Gatling?

Sinisa Brzak picture Sinisa Brzak · Jan 16, 2018 · Viewed 10.2k times · Source

I've tried different approaches that I've found on Gatling.io, but my problem still persists. There's an API which returns a short response in JSON format when I send a GET request.

GET request:

http://localhost:some_port/api/endpoint1?parameter1=1234&parameter2=5678

Response:

{"transaction":"6d638b9b-f131-41b1-bd07-0d1c6a1d4bcc","reference":"some_text"}

I need to get transaction value from the response and use it in another request.

Next request:

http://localhost:some_port/api/endpoint2?transaction=$transactionValue&parameter=8

So far I've tried using regex, jsonPath with Int or String values but the result is 0 or None.

This is my scenario code so far:

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

class class1 extends Simulation {

    val httpProtocol = http
        .baseURL("http://localhost:port")
        .inferHtmlResources()
        .acceptHeader("text/html,application/json")
        .acceptEncodingHeader("gzip, deflate")
        .acceptLanguageHeader("en-US,en;q=0.9,hr;q=0.8,sr;q=0.7,bs;q=0.6")
        .userAgentHeader("Mozilla/5.0 (X11; Fedora; Linux x86_64)")

    val headers = Map(
        "Content-Type" -> "application/json")

    val uri1 = "http://localhost:port/api/endpoint1"
    val uri2 = "http://localhost:port/api/endpoint2"

    val scn = scenario("getEndpoint1")
        .exec(http("endpoint1")
            .get("/api/endpoint1?parameter1=1234&parameter2=5678")
            .headers(headers)
      .check(jsonPath("$.transaction").findAll.saveAs("transaction")))
    .pause(3)
    .exec(session => {
      val transaction = session("transaction").asOption[String]
      session
    }).exec(http("endpoint2").get(uri2 +s"/transaction=${"transaction"}&parameter=8").headers(headers))

    setUp(scn.inject(atOnceUsers(1))).protocols(httpProtocol)
}

If you have any suggestions or see something I'm doing wrong, it will be greatly appreciated.

Answer