Reuse {{$randomInt}} in Postman
Asked Answered
R

1

5

My 1st request is: GET http://example.com?int={{$randomInt}}. I need to run 2nd request (with other tests in it) to the same address, so I need to save generated variable. How can I do it?

I was trying pm.variables.get("int") in the "Tests" sandbox after 1st request, but this code cannot see int var.

Creating random number in Pre-req. sandbox to 1st request: postman.setGlobalVariable('int', Math.floor(Math.random() * 1000)); doesn't help either, because I need to use this param in the URL, while "Pre-req." block is run after request but before tests.

So how can I generate random var before 1st request and store it to use in 2nd request?

Requisition answered 10/1, 2018 at 9:47 Comment(1)
Do you need to use {{$randomInt}} once and then a different value in a 2nd request. The question is slightly confusing and hard to follow.Preamble
P
13

If you set this in the Pre-Request Script of the first request:

pm.globals.set('int', Math.floor(Math.random() * 1000))

Or

// Using the built-in Lodash module
pm.globals.set("int", _.random(0, 1000))

You will be able to reference it and use the {{int}} syntax in any request. If you add this in the first request and then use it in the URL http://first-example.com?int={{int}} this value will then persist and you can use it again in a second request http://second-example.com?int={{int}}

Each time that {{$randomInt}} is used, it will generate a new value at run time.

Preamble answered 10/1, 2018 at 9:56 Comment(2)
Yeah, I know that I need to use already generated variable and not again {{randomInt}} for the 2nd time. So I was using wrong syntax in Pre-req. Thanks!Requisition
Cool, hope the solution helps. :)Preamble

© 2022 - 2024 — McMap. All rights reserved.