rvsntn
rvsntn

Reputation: 85

Modify a JSON response to send back to the api in Gatling/Scala

I am doing some Gatling and since I never do scala, I am kind of lost. I want to modify the JSON response from a JsonPath I receive before sending it back

My code look like this

  .exec(
    http("Get call")
      .get("getEndpoint")
      .check(jsonPath("$.value").saveAs("RESPONSE_DATA"))
  )
  .exec(
    http("Post call")
      .post("postEndpoint")
      .header("content-type", "application/json")
      .body(StringBody("${RESPONSE_DATA}"))
      .asJson
  )

For example, I want to change to the first name of the user receive in Json from the Get Call. I can't manage to find an answer to Gatling documentation

Upvotes: 0

Views: 1967

Answers (1)

rvsntn
rvsntn

Reputation: 85

Thanks to Lars comment, I manage to find a solution. I was too focus on finding the specific method for Gatling that I forgot the basic way to do programming

Here the new code

  .exec(
    http("Get call")
      .get("getEndpoint")
      .check(jsonPath("$.value").saveAs("RESPONSE_DATA"))
  )
      .exec(session =>
        {
          // put body response into variable
          val response = session("RESPONSE_DATA").as[String];
          // generate random string as you convenience
          val randomString = Random.alphanumeric.filter(_.isLetter).take(5).mkString;
          // use replace method to modify your json (which is right now a string)
          newResponse = response.replace(
            """specificKey":""",
            """specificKey":""" + randomString + "",
          )
          session
        }.set("RESPONSE_DATA", newResponse)
        // ^ really important to set the new value of session outside of brackets !!
      )
  .exec(
    http("Post call")
      .post("postEndpoint")
      .header("content-type", "application/json")
      .body(StringBody("${RESPONSE_DATA}"))
      .asJson
  )

Upvotes: 1

Related Questions