Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse {{$randomInt}} in Postman

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?

like image 820
Shurov Avatar asked Jan 10 '18 09:01

Shurov


People also ask

How do you generate a random 9 digit number in Postman?

We can use Postman built-in variable randomInt to generate random integer value. We can generate random/dynamic data in requests using the following functions. $randomInt.

How do you generate random alphanumeric string in Postman?

Code for your Pre-request Script tab in Request: function randomString(length=1) { let randomString = ""; for (let i = 0; i < length; i++){ randomString += pm. variables. replaceIn("{{$randomAlphaNumeric}}"); } return randomString; } STRING_LEN = 1000 pm.

How do you pass dynamic value in Postman?

A dynamic variable name starts with '$. ' In the request URL section, a dynamic variable should be written in {{__}} format. Let's say you have to pass an integer number from 1 to 1000, so for that, you need to add {{$randomInt}}.


1 Answers

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.

like image 161
Danny Dainton Avatar answered Sep 24 '22 02:09

Danny Dainton