37
votes

I need to generate random number in specific range for postman. I wonder if there is possible to generate it and to use it in variable in postman, from what I saw at postman site is:

{{$randomint }}

will give random number between 1-1000 and I already tried to do something like this:

{{$randomint(1,5)}}

to get number between 1-5 but postman didn't get this kind of option, so how to specify range for the random in postman?

4
Just use the built-in functionality and a little bit of math. Round, divide, multiply - Roberto Zvjerković
also did try {{$randomint(math.random()*3}} - user8144993
Did either of the solutions answer your question? - Danny Dainton
no, neither of them workes - user8144993
Do you still need an answer for this? - Danny Dainton

4 Answers

49
votes

You can just use Lodash for this as it's a built-in module:

pm.environment.set("random_number", _.random(1, 5))

Or just add the number 5 to the _.random() function and this will be a number from 0 to 5.

23
votes

This worked for me:

In your Pre-request script define your variable with:

pm.globals.set('randomNumber', Math.floor(Math.random() * 5));

Then in your URL call your variable in the URL like so:

{{randomNumber}}

Hope this works for you.

7
votes

A little late. But none of the above answers worked for me. I solved it by setting a variable in pre-request tab.

Example:

pm.collectionVariables.set ("randomNum", _.random (20,100));

Then use the variable name in the body of my request (like any other variable)

{
    "number": {{randomNum}}
}

Finally, this generates a new number between the desired values in each request

5
votes

Just use the modulo operation:

const num = pm.variables.replaceIn('{{$randomInt}}') % 5 + 1;
pm.environment.set("random_number", num);

// test
console.log(pm.variables.get('random_number'));