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?
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!
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 yes this looks perfect 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
To explore more about Loadash, check their official site.
hope you can help
i have tried following
var journalId = [‘12864E’, ‘41467E’,‘345E’];
pm.globals.set(“journalid”, journalId[_.random(journalId.lenght-1)]);
Three elements is not a very large set of test data, so it might appear to be the first value each time.
I would recommend using the lodash sample library instead of random.
I’ve put the following in a loop, so you can see that it does indeed use each of the test data elements.
var journalId = ["12864E", "41467E","345E"];
for (let i = 0; i < 10; i++) {
console.log(_.sample(journalId));
};
and the console log.
Do you really need this to be a global variable??
var journalIds = ["12864E", "41467E","345E"]; // don't call the test data and collection\global variable the same thing
pm.collectionVariables.set("journalid", _.sample(journalIds));
console.log(pm.collectionVariables.get("journalid"));