How to pass dynamic json request body in postman

16,042

Solution 1

You ca do it by adding

var rnd = Math.floor((Math.random() * 10000) + 1);
postman.setEnvironmentVariable("firstname", "fname"+rnd);
postman.setEnvironmentVariable("lastname", "lname"+rnd);

in the Pre-request Script section.

And then adding

{ 
"firstName":"{{firstname}}", 
"middleName":"mani", 
"lastName":"{{lastname}}" 
} 

in the body.

I tried it in both Postman and Newman and is working perfectly generating a random first name and last name.

Solution 2

{ 
 "request": { 
   "firstName":"{{$randomInt}}",
   "middleName":"mani",
   "lastName":"{{$randomInt}}" 
  }
}

No need to add global variables. Postman have dynamic variable {{$randomInt}} which Adds a random integer between 0 and 1000

Share:
16,042
Div
Author by

Div

Updated on June 13, 2022

Comments

  • Div
    Div about 2 years

    I have a POST request where i need to pass some parameters dynamically since my code is checking for a duplicate entry. I tried writing a pre request script and then setting the global variables and tried to access it in my request. It is not working. PFB, the details

    Pre-request Script

    postman.setGlobalVariable("firstname", (text + parseInt(Math.random()*10000)).toString()); postman.setGlobalVariable("lastname", text + parseInt(Math.random()*10000));

    Body

    { "request": { "firstName":"{{firstname}}", "middleName":"mani", "lastName":"{{lastname}}" } }

    Here firstName is getting passed as {{firstname}} instead of random string.