Edit request body depending on falsy variables?

Hi,

Is it possible write a pre-request script that will tell Postman to remove or ignore a parameter in the request body if a certain variable is falsy?

I’m trying to create a collection and one of the requests has parameters that must either have a value or be omitted from the request; a null value will return an error.

Can you show an example request?

Is it a GET request using query parameters, or a POST request with a JSON body.

Can you show how the variable you want to check is being set. (Is it an Environment or Collection variable or something else).

<addCustomerDiscount>
<templateId>{{}}</templateId>
<customerId>{{}}</customerId>
<currency>{{}}</currency>
<maxDiscount>{{}}</maxDiscount>
<discountExpiryDate>{{}}</discountExpiryDate>
<discountId>{{}}</discountId>>
<productIdList>{{}}<productIdList>
</addCustomerDiscount>

This is a POST request. Collection variables are used. {{}} are used to denote where a collection variable will be provided.

In this request the templateId parameter must either have a value or be omitted / ignored.

This would be fairly easy to do if it was JSON.

You would check the collection variable and if its doesn’t exist or is null, you would then save the current request body to a variable. Remove the key with the null value in it, then set the updated variable as the new body. Effectively overwriting the entire body of the request.

That is XML, so I’m not 100% sure how easy it is to do the same trick. I’ll have to play around with it first.

Can you confirm how the body is configured. Is it RAW\Text or RAW\XML?

Thanks.

It’s RAW\XML.

You can use something like…

// Store the current body into a variable.
let body = pm.request.body.raw;
console.log(body);
// break the body\text into an array of lines
let lines = body.split('\n');
// remove the maxdiscount line
lines.splice(4,1);
// join the array back into a single string
var newBody = lines.join('\n');
console.log(newBody);
// set the new body back into the request
pm.request.body.raw = newBody

I’ve hardcoded this to just delete the maxdiscount line, but you can wrap this in an IF statement that looks for the existence of the collection variable.