1

I am new to Postman. I have dabbled with automating some of my API calls here in I set counters and randomize characters. 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 used in the API call.

For example, storing a list of 1000 US Cities. For this example, lets 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?

  • What did you already try? Please share your code. Thanks for considering [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) and [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). – Christian Baumann Apr 01 '21 at 13:54

3 Answers3

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

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

PDHide
  • 18,113
  • 2
  • 31
  • 46
1

You can do this with a pre-request script in your collection. That way your list of cites/items will be available for all the requests in your collection.

  1. Select your collection in Postman
  2. Go to the Pre-request Script tab (these scripts will run before every request in the collection, so you will get a random value each time)
  3. Add code to select a random value and assign it to a variable, example below
//Available Items
var itemsAvailable = 
[
    "Item1",
    "Item2",
    "Item3"
];

//Pick an Item
var item = _.sample(itemsAvailable);

//Log it to console for debugging
console.log("Item Picked: " + item);

//Set our variable so it can be used in requests via {{MyVariable}}
pm.environment.set("MyVariable", item);
  1. Now update your request and use the variable {{MyVariable}} which will contain a random value from the list defined above.

The {{MyVariable}} may not show up in the intellisense until you execute at least one request with the pre-request script and the variable gets added to the environment. This script will also output to the console the value that was chosen to assist in debugging.

GER
  • 1,870
  • 3
  • 23
  • 30
0

Add all the values of the cities in an array, then use the below code snipped to randomly select one of the city

var cities = ["San Francisco", "San Diego", "Boston"];
pm.environment.set("CITY", cities[Math.floor(Math.random() * cities.length)]);

Edit the Body of your POST request to pass the CITY variable

{
  "city":"{{CITY}}"
}
CostaIvo
  • 1,029
  • 13
  • 19