Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postman - how to generate random number in specific range?

Tags:

random

postman

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.


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.


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


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'));