Peter
Peter

Reputation: 45

How to seed the request body directly from the pre request script on postman

I created JSON object (movieData) and saved it as a global variable (all my test cases). I want to get part of the data (everytime single case) and send it to request body from the pre-request script.

const movieData = {
   env: "testing",
   domain: "",
   tests: {
     test1: { 

       body: {
         movie_id: 568,
         title: "wonder-woman",
         description: "bla bla bla",
       }
       .... 
     },
     test2: { 

       body: {
         movie_id: 232,
         title: "spider-man",
         description: "bla bla bla",
       }
       .... 
     },
     test3: { 

       body: {
         movie_id: 212,
         title: "just-woman",
         description: "bla bla bla",
       }
       .... 
     },
     test4: { 

       body: {
         movie_id: 534,
         title: "just-man",
         description: "bla bla bla",
       }
       .... 
     }

   }
}

pre-request:

var movies = JSON.parse(pm.globals.get('movieData')); const test = movies.tests.test1.body; pm.globals.set('test', test);

body:

"{{test}}"

Anyone help how to do that?

Upvotes: 1

Views: 7675

Answers (2)

elburro1887
elburro1887

Reputation: 64

Pre-request script

var jsonData = {
  "method": "test",
  "params": {
    "token": "hello"
  },
  "moreData": "2.0"
};


pm.globals.set("myreqbody", JSON.stringify(jsonData));

Body

{{myreqbody}}

Upvotes: 0

Rohit Kumar
Rohit Kumar

Reputation: 1792

it is easier then you think... a " " would to the dynamic adding trick

as per docs.. the dynamic variable are to be

this is my email body..

{
    "email": "{{email}}",   //notice the " " quotes
    "password": "cityslicka"
}

enter image description here

I am dynamically changing the {{email}} and {{target}} in the pre-request scripts ...

Notice : {{target}} is in URL without quotes where "{{email}}" is in the body and has 'em " "

enter image description here

Upvotes: 3

Related Questions