I'm new at postman an im trying to generate a random string with letters(A-Z) and numbers(0-9). The string should have 20 points. I don't know how to set the Body and the pre req. I know that the Request must be POST. I have no idea how to start.
You can add scripts to the Pre-request Script
to create this value.
This function will create the random value from the characters in the dataset
and it will be 20 characters in length - The length can be adjusted when calling the function with your desired min and max values.
function randomString(minValue, maxValue, dataSet = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ') {
if (!minValue) {
minValue = 20;
maxValue = 20;
}
if (!maxValue) {
maxValue = minValue;
}
let length = _.random(minValue, maxValue),
randomString = "";
for (let i = 0; i < length; i++)
randomString += dataSet.charAt(Math.floor(Math.random() * dataSet.length));
return randomString;
}
pm.variables.set('randomString', randomString());
Adding a basic body like this is how you can use the randomly generated value:
{
"randomValue": "{{randomString}}"
}
When the request is sent, it will execute the function in the Pre-request Scripts
tab and set the value as a local variable, this will then be used in the body of the request:
Per postman's docs you should be able to use {{$randomAlphaNumeric}}
to generate a single character. $randomPassword seems to just generate 15 random alpha numeric characters so something like:
{{$randomPassword}}{{$randomAlphaNumeric}}{{$randomAlphaNumeric}}{{$randomAlphaNumeric}}{{$randomAlphaNumeric}}{{$randomAlphaNumeric}}
should give you 20 random characters without writing much code. This is a little terse, you could also just use the $randomAlphaNumberic selector 20 times.
Code for your Pre-request Script
tab in Request:
function randomString(length=1) {
let randomString = "";
for (let i = 0; i < length; i++){
randomString += pm.variables.replaceIn("{{$randomAlphaNumeric}}");
}
return randomString;
}
STRING_LEN = 1000
pm.variables.set('randomString', randomString(STRING_LEN));
Just set the STRING_LEN
to desired value.
Test it by using expression {{randomString}}
i.e. in URL:
https://httpbin.org/anything?string={{randomString}}
Here's another cleaner solution that works just fine in Postman
// Generate a random 10-character string using built-in dynamic variable and substring
const randomString = pm.variables.replaceIn('{{$randomUUID}}').substring(0, 10);
pm.environment.set('partner_transaction_id', randomString);
console.log('partner_transaction_id:', randomString);
© 2022 - 2024 — McMap. All rights reserved.