How to change request body before sending request

I need to change the request body data before sending to server. I’m loading data from a json file.
Json file may have array values for few fields. So, those fields need to be passed as array in url-encoded-form data. This is server restriction. We can’t change in server.

Json will have data as

“days”:[1,2,3,4,5],
“month”:[2,3,4]

To server , these fields should be passed in url-encoded-form-data as below.

days[] : 1
days[] : 2
days[] : 3
days[] : 4
month[]: 2
month[]: 3
month[]: 4

Note: Values for above fields are dynamic in count.

I did small script in pre-request script section.

Removed existing empty field for days.

pm.request.body.urlencoded.remove(‘days’);

Added values from iteration data.
let data_for_key = pm.iterationData.get(‘days’);
let data_len = data_for_key.length;
for(var j=0; j<data_len; j++){
let obj = {};
obj[‘days’] = data_for_key[j];
pm.request.body.urlencoded.insert(obj);
}
console.log(“updated - body”,pm.request.body.urlencoded);

console.log gives updated request body. but request sent with old request body instead of updated one.

Am I missing anything? Please help to make it work.

Hi @mockdev_postman, welcome to the community! :wave:

There are couple of solutions already present in the community (I just searched for these):
Search Query: Search results for 'Dynamic request body' - Postman Community

Couple of results that point towards the similar kind of problem:

Hi @singhsivcan, Thanks for your reply.

My requirement is for urlencoded-form-data. Also, input variable count is dynamic, then i can’t use environment variables. Because empty values are not allowed.

Can you please go through my code and suggest anything?

I have already used environment variables heavily and i came to know that env variables are not suitable for my dynamic number of input parameters.

Thanks

@singhsivcan
Can you please help me on this? I just want to modify the request body before request sent.
I’m reading data from json and few fields will have array of data. So I need to loop through those array fields data and create urlencoded params with the name field_name repetitively .

Thanks

  1. You cannot modify the request body using the scripts, that’s why your existing script isn’t working for you.
  2. Here’s a solution written by @matt: https://github.com/postmanlabs/postman-app-support/issues/5553#issuecomment-440766842
    Make sure that you’ve set the Header to form urlencoded
Content-Type: application/x-www-form-urlencoded

try using:

pm.request.body.urlencoded.add({ key: 'yourfield', value:'yourvalue' });