Modify query param in pre-request script

I need to programmatically set a query parameter on my request. Up until a week or two ago I was able to do the following, and it worked:


// update param1 to new value
let queryParam1 = 'whatever';
pm.request.url.query[0] = queryParam1;

This doesn’t work anymore. How do I modify (or add) a query parameter to my request in the pre-request script?

1 Like

Seems I can do it like this now, but I’d still like to know if there’s a “right” way so my scripts don’t break again:

pm.request.url.query.add(‘param1=’ + paramValue);

1 Like

So I’m pretty new to postman scripting, but I think this might work for you. If I know the index of my parameter to update, as it seems you are wanting to do, I have been successful with

pm.request.url.query.idx(0).value = "newValue";

In your pre-request script, set a variable, e.g.

postman.setEnvironmentVariable(“queryParam1”, “whatever”);

Then you can use {{queryParam1}} in your query parameters just like you set the rest of them.

What actually worked for me all the time was:

//console.log("----- Encode query string");
//console.log("Input: " + pm.request.url.query.toString());
var querycount = pm.request.url.query.count();
for(let i = 0; i < querycount; i++) {
  //console.log(i + "/" + pm.request.url.query.idx(i).key + ": " + encodeURIComponent(pm.request.url.query.idx(i).value));
  pm.request.url.query.idx(i).value = encodeURIComponent(pm.request.url.query.idx(i).value);
//console.log("Output: " + pm.request.url.query.toString());

to add query params there is 2 ways


you can loop over pm.request.url.query it is an array of objects, every object has 3 properties

     disabled: true, // only if it is disabled 
     key: "auth_username",
     value: "{{username}}",

you can find what you are looking for and set it like you wan’t

This pre-request might be useful for those wishing to modify a single named query parameter:

const { key, value } = pm.request.url.query.find(q => q.key === 'myParam')
1 Like

I have created a generic function for adding query params to request query. It will update or insert request query based on the key. It does extra check for the key is it falsey and make value empty string if value is falsey.

function upsertQueryParams(key, value) {
    if (!key) {
        throw new Error('Empty query param key.');

    pm.request.url.query.upsert({ key, value: value || '' });

And the usage will be

upsertQueryParams('yourParamKey', 'paramValue');