# How to make one HTTP request before the scenario?

**URL:** <https://community.gatling.io/t/how-to-make-one-http-request-before-the-scenario/2932>\
**Category:** Gatling (Open-Source)\
**Created:** [April 18, 2016, 10:45am UTC](https://community.gatling.io/t/how-to-make-one-http-request-before-the-scenario/2932 "2016-04-18T10:45:25Z")\
**Posts on this page:** 15\
**Page:** 1

<div class="post-metadata">

**Author:** ![Dmitry\_Bedrin](https://avatars.discourse-cdn.com/v4/letter/d/cdc98d/32.png) [@Dmitry\_Bedrin](https://community.gatling.io/u/Dmitry_Bedrin)\
**Post date:** [April 18, 2016, 10:45am UTC](https://community.gatling.io/t/how-to-make-one-http-request-before-the-scenario/2932/1 "2016-04-18T10:45:25Z")

</div>

Hi guys,

I’m trying to use gatling for testing following use case:1) Authenticate using REST endpoint /login/ and obtain a session cookie  
2) Make 100K requests to other services with this cookie

I would like to make the first request using the gatling API in order to use the same HTTP properties (proxy, e.t.c.)

I can see that build method of PopulationBuilder is private to io.gatling.core and I cannot call it directly

What’s the best way to implement it in gatling?

Thanks,  
Dmitry

---

<div class="post-metadata">

**Author:** ![jarrowwx](https://avatars.discourse-cdn.com/v4/letter/j/4af34b/32.png) [@jarrowwx](https://community.gatling.io/u/jarrowwx)\
**Post date:** [April 18, 2016, 1:46pm UTC](https://community.gatling.io/t/how-to-make-one-http-request-before-the-scenario/2932/2 "2016-04-18T13:46:07Z")

</div>

I’ve implemented this very type of thing before. It’s doable.

Assuming you don’t want to make 100k requests in serial, you want all your requests to be executed like a normal scenario, so you can take advantage of the traffic shaping abilities of Gatling…

Option 1: Create a thread-safe token cache object. When you request the token for the first time, it communicates with the server to fetch the token. Once it has the token, it caches it and on future requests, it returns the cached token. In the mean time, any calls to the cache looking for a token while the token is being fetched need to block.

Option 2: Fetch the token during scenario build time. You won’t be using Gatling DSL to fetch it, so you will have to implement it differently.

Option 3: Create a Gatling scenario that all it does is request the token, and writes it to a file. Then you build your test to feed the token from that file. Then when you launch your test, you launch it using a batch file or shell script which first launches the token-getter scenario, then when it completes, it launches the real test.

Option 3 is the easiest to implement, from a complexity standpoint.

I’ve even gone farther, and got access to the database and gave the token a lifetime of 1 year, so I could do it once, and then cache it, and not have to re-run the token-fetching code very often. But that’s because I needed hundreds of thousands of tokens, not just one, and the cost of creating the tokens was significant.

Hope this helps.

---

<div class="post-metadata">

**Author:** ![Dmitry\_Bedrin](https://avatars.discourse-cdn.com/v4/letter/d/cdc98d/32.png) [@Dmitry\_Bedrin](https://community.gatling.io/u/Dmitry_Bedrin)\
**Post date:** [April 26, 2016, 1:01pm UTC](https://community.gatling.io/t/how-to-make-one-http-request-before-the-scenario/2932/3 "2016-04-26T13:01:44Z")

</div>

Thanks, John!

I went with option 1 and it worked just fine!

---

<div class="post-metadata">

**Author:** ![Pavel\_Golub](https://avatars.discourse-cdn.com/v4/letter/p/ee7513/32.png) [@Pavel\_Golub](https://community.gatling.io/u/Pavel_Golub)\
**Post date:** [December 14, 2017, 3:41pm UTC](https://community.gatling.io/t/how-to-make-one-http-request-before-the-scenario/2932/4 "2017-12-14T15:41:23Z")

</div>

Dmitry, do you have a code sample how did you do it? I’m pretty new in this area.

---

<div class="post-metadata">

**Author:** ![Pavel\_Golub](https://avatars.discourse-cdn.com/v4/letter/p/ee7513/32.png) [@Pavel\_Golub](https://community.gatling.io/u/Pavel_Golub)\
**Post date:** [December 15, 2017, 11:30am UTC](https://community.gatling.io/t/how-to-make-one-http-request-before-the-scenario/2932/5 "2017-12-15T11:30:00Z")

</div>

I’ve got this finally working. So leaving code snippet for others

`

```auto
object Scenarios {
  var tokens: Map[String, String] = Map[String, String]()

  def searchScenario: ScenarioBuilder = scenario("search-scenario").during(Configuration.TestDuration) {
    feed(Feeders.userAccount).doIf(session => tokens.get(session("userName").as[String]) == None) {
      exec(
        http("Token")
          .get("tokens/")
          .basicAuth("${userName}", "${password}")
          .check(status.is(200))
          .check(jsonPath("$[*].Id").ofType[String].saveAs("session-token"))
      ).exec(session => {
        tokens += (session("userName").as[String] -> session("session-token").as[String])
        session
      })
    }
      .feed(Feeders.searchQuery)
      .exec(http("Search")
        .get("/search")
        .queryParam("q", "${q}")
        .header("Authorization", "Token ${session-token}"))
  }
}

```

`

---

<div class="post-metadata">

**Author:** ![Maksym\_Max](https://avatars.discourse-cdn.com/v4/letter/m/ecc23a/32.png) [@Maksym\_Max](https://community.gatling.io/u/Maksym_Max)\
**Post date:** [December 29, 2017, 10:45am UTC](https://community.gatling.io/t/how-to-make-one-http-request-before-the-scenario/2932/6 "2017-12-29T10:45:25Z")

</div>

Is it a good way to use Map instead of concurrent version?

---

<div class="post-metadata">

**Author:** ![slandelle](https://dub1.discourse-cdn.com/flex013/user_avatar/community.gatling.io/slandelle/32/4_2.png) [@slandelle](https://community.gatling.io/u/slandelle)\
**Post date:** [December 29, 2017, 4:26pm UTC](https://community.gatling.io/t/how-to-make-one-http-request-before-the-scenario/2932/7 "2017-12-29T16:26:54Z")

</div>

It’s not 🙂

---

<div class="post-metadata">

**Author:** ![Lukasz\_Yabol](https://avatars.discourse-cdn.com/v4/letter/l/ea666f/32.png) [@Lukasz\_Yabol](https://community.gatling.io/u/Lukasz_Yabol)\
**Post date:** [September 25, 2018, 1:54pm UTC](https://community.gatling.io/t/how-to-make-one-http-request-before-the-scenario/2932/8 "2018-09-25T13:54:43Z")

</div>

@Pavel Golub

The first request is executed only once?  
I have a similar problem, I need to grab some data first and then reused it until now I kept a static list but it’s changing too often.  
I did a similar thing

```auto
object FiltersTest{

  def getFilters(duration:Duration)= {
    exec(
      http("Get filter from metadata")
        .get("/api/v2/metadata?Tenant=" + Tenants.Flex)
        .check(status.is(200))
        .check(jsonPath("$..filtersDescriptors..name").findAll.saveAs("filterList"))
    )

```

```auto
    .during(duration, exitASAP = false) {
     foreach("${filterList}", "filter") {
        exec(
          http("Get filter ${filter}")
            .get("/api/v2/filter-value/${filter}?startDate=" + Constants.startDate + "&endDate=" + Constants.startDate + "&PyraCloudTenant=" + Tenants.Flex)
            .check(status.is(200))
            .check(jsonPath("$..key").count.greaterThan(0))
        ).pause(Constants.pauseDuration)
      }
    }
  }
}

```

But the first request is executed the same number of times as the foreach inside during{} block.

I’m missing something ?  
I know that I could save it to file as John mentioned but it’s a little bit stupid in my opinion.

Regards  
Lukasz

---

<div class="post-metadata">

**Author:** ![Julia](https://avatars.discourse-cdn.com/v4/letter/j/2bfe46/32.png) [@Julia](https://community.gatling.io/u/Julia)\
**Post date:** [September 25, 2018, 9:38pm UTC](https://community.gatling.io/t/how-to-make-one-http-request-before-the-scenario/2932/9 "2018-09-25T21:38:55Z")

</div>

Hi Lukasz,  
I think with your code example you need to input 1 user in setup, then it will fetch filterList once, and then generate the number of requests of length of filterList.

---

<div class="post-metadata">

**Author:** ![Lukasz\_Yabol](https://avatars.discourse-cdn.com/v4/letter/l/ea666f/32.png) [@Lukasz\_Yabol](https://community.gatling.io/u/Lukasz_Yabol)\
**Post date:** [September 26, 2018, 10:24am UTC](https://community.gatling.io/t/how-to-make-one-http-request-before-the-scenario/2932/10 "2018-09-26T10:24:23Z")

</div>

Thank’s Julia,  
True I was running it for a number of users, with one user I get what I expected.

But it means that first request will be executed for each user, not exactly what I need.

So we back to saving in the file it’s a pity that gatling doesn’t have run once option and you have to do  
workarounds ☹

Regards

---

<div class="post-metadata">

**Author:** ![slandelle](https://dub1.discourse-cdn.com/flex013/user_avatar/community.gatling.io/slandelle/32/4_2.png) [@slandelle](https://community.gatling.io/u/slandelle)\
**Post date:** [September 26, 2018, 10:53am UTC](https://community.gatling.io/t/how-to-make-one-http-request-before-the-scenario/2932/11 "2018-09-26T10:53:03Z")

</div>

[https://gatling.io/docs/3.0/general/simulation\_structure/?highlight=before#hooks](https://gatling.io/docs/3.0/general/simulation_structure/?highlight=before#hooks)

---

<div class="post-metadata">

**Author:** ![Lukasz\_Yabol](https://avatars.discourse-cdn.com/v4/letter/l/ea666f/32.png) [@Lukasz\_Yabol](https://community.gatling.io/u/Lukasz_Yabol)\
**Post date:** [September 26, 2018, 11:17am UTC](https://community.gatling.io/t/how-to-make-one-http-request-before-the-scenario/2932/12 "2018-09-26T11:17:58Z")

</div>

Hi Stéphane,

I know that there is before method but still, it required to write custom code or in v3 this will change and it will be possible to use DSL ?

Regards

---

<div class="post-metadata">

**Author:** ![slandelle](https://dub1.discourse-cdn.com/flex013/user_avatar/community.gatling.io/slandelle/32/4_2.png) [@slandelle](https://community.gatling.io/u/slandelle)\
**Post date:** [September 26, 2018, 11:18am UTC](https://community.gatling.io/t/how-to-make-one-http-request-before-the-scenario/2932/13 "2018-09-26T11:18:53Z")

</div>

Still works the same way.

---

<div class="post-metadata">

**Author:** ![Julia](https://avatars.discourse-cdn.com/v4/letter/j/2bfe46/32.png) [@Julia](https://community.gatling.io/u/Julia)\
**Post date:** [September 26, 2018, 12:54pm UTC](https://community.gatling.io/t/how-to-make-one-http-request-before-the-scenario/2932/14 "2018-09-26T12:54:38Z")

</div>

You can try to divide your requests to separate ChainBuilder objects and pass the values between two sessions by saving fetched list to external object:

`.exec { session => someExternalVar = session("fetchedAttribute") session}`

And then setting it as a session attribute:

`.exec(_.set("attributeToBeUsedAfter", someExternalVar))`

Then you can have different number of users for them. I think this scheme is good enough for authorisation (fetching token), but for similar situation as yours I use saving to files and running simulations in sequence, as you can use standard csv feeder then.

---

<div class="post-metadata">

**Author:** ![Lukas\_Lukyer](https://avatars.discourse-cdn.com/v4/letter/l/e36b37/32.png) [@Lukas\_Lukyer](https://community.gatling.io/u/Lukas_Lukyer)\
**Post date:** [July 26, 2019, 10:26am UTC](https://community.gatling.io/t/how-to-make-one-http-request-before-the-scenario/2932/15 "2019-07-26T10:26:56Z")

</div>

Hi all, I managed to do what you want but only in hacky way:

val initStarted = new AtomicBoolean(false)  
val initCompleteLatch = new CountDownLatch(1)

scenario(“myScenario”)  
.doIf(\_ =\> initStarted.getAndSet(true) == false) {  
exec(http(“first”)  
.get("/endpoint")  
.check(status.is(200),  
jsonPath("$…response.id").findAll.saveAs(“reponseVariable”)  
)  
).exec { session =\>  
reponseVariable = session(“reponseVariable”).as[String]  
initCompleteLatch.countDown()  
session  
}  
}  
.exec { session =\>  
initCompleteLatch.await()  
session.set(“reponseVariable”, reponseVariable)  
}  
.exec(http(“second”)  
.post("/another/endpoint/{responseVariable}")  
.body(…)  
.check(status.is(200))  
)

Hope it helps 🙂 It can chain serveral requests, passthrough response along, and ensures first request is send only once.

Btw it was so disappointing about Gatling that one have to do such dirty hacks to achieve so common thing ☹
