How to store a list of value and then send one of those values randomly in an API call?

I am new to Postman, but learning. I have dabbled with automating some of my API calls here in I set counters and randomize characters where a unique identifier is required.

However, I need to store a list of values (for this exercise it could be 1000 individual values) and then randomize which value is being sent in the API call.

For example, storing a list of 1000 US Cities. For this example, let’s use the three below.

San Diego, San Francisco, Louisville

Then when I make the API call via POST, I send a random value (e.g. a city) from the list of 1000 cities. How can this be achieved in Postman?

1 Like
_.sample(['January', 'February', 'March'])

create a list of 1000 items and use lodash sample function to select random element from it

1 Like

Dumb question, but can I store the list in the pre-req script and then call it in the JSON payload? I am not sure if it works this way. Thanks for the help!

yes as variable store list or what ever you want as variable:


now can call it in request as {{somename}}

I got that far, it was the pulling a random value that has been throwing me off.

For example:

postman.setEnvironmentVariable(‘Cities’,“San Francisco”, “San Diego”, “Boston”);

    "Location": {
        "randomCity": "{{Cities}}",

This is always returning San Francisco as I assume it is first in the list. In looking through Postman documentation I was having a hard time finding what allows you to pull one at random.

Hi @jarrodedg :wave:

If you are going to pick the defined array, it should declared as below.

var Cities = ["San Francisco", "San Diego", "Boston"];


pm.environment.set("CITY", Cities[Math.floor(Math.random() * Cities.length)]);

After assigning the array to a variable, the last line is for pick the random cities from the defined array.

Now body of the request should contain,

    "Location": {
        "randomCity": "{{CITY}}",

From the defined array, among the three values it will pick one for every single hit. Is this is your expectation? :blush:

It looks like that would work. I achieved via a different means. See below:

var randomCity = [“Portland”,“San Francisco”,]

Is there a benefit to one approach versus the other?

1 Like

Hi @jarrodedg yes this looks perfect :+1: Let me explain the differences.

Firstly when you try to understand the script, we are generating a random number based on length of the array.

Basic difference is, I have used inbuilt JS functions to derive the random number to pass as index for the array.

You have used Loadash libraries to generate the random number. Both are efficient enough.

Picking them depends on the user. In this example there’s not much difference to the lines of code. Sometimes using loadash the code snippets will look simple and fancy :smiley:

To explore more about Loadash, check their official site.

I hope it helps :blush: