Check if data variable exists and if not, apply default value

Is there a way to check if a data variable is empty and if so, enter a default value?

For example, say my request body is:

{
  id: {{id}},
  name: {{name}},
  reference: {{reference}}
}

but my data file only contains:

{
  id: 1,
  name: "Russell"
}

Instead of the request body sending:

{
  id: 1,
  name: "Russell",
  reference: {{reference}}
}

It instead sends:

{
  id: 1,
  name: "Russell",
  reference: null
}

Is there a way to do a check for this?

I am trying to keep my data files small so I do not have to pass so many needless null values and instead have some logic to detect if the data variable exists.

Could you try something basic in your Pre-request Script like this:

if(!pm.iterationData.has("reference")) {
    pm.variables.set("reference", "default_value")
}

If the reference key is not part of the data file, it will create a local variable thatโ€™s used during the run.

Hi Danny,

That does work. However I have many variables for each endpoint and it requires a solution where I am not hardcoding variable values. Itโ€™s a good start though

Itโ€™s a start at least :slight_smile:

If you can provide a cut-down example of the data file and request body - Iโ€™m sure that it can be done.

This can be done where you get the iteration data as an object, get all the keys and then add some form of logic around a certain condition. That can then, in turn, create a default variable to use.

const dataKeys = _.keys(pm.iterationData.toObject())

_.each(dataKeys, (arrItem) => {
    if (arrItem.startsWith("reference_")) {
        pm.variables.set(arrItem, "default_value")
    }
});

Without more specific information Iโ€™m just guessing at a solution though.

Request Body:

{
  "citizenshipCode": {{cz_citizenshipCode}},
  "date": {{cz_date}},
  "visaInd": {{cz_VisaInd}},
  "type": {{cz_type}},
}

Data file may only contain say, for example:

"cz_citizenshipCode": "6105",
"cz_type": 5

In that case the two values where the data file (in this instance or scenario) does not have the other two values, they should default to null.

Hope that helps.

Repiled privately but posting again here for others, just in case they know a better solution for this problem.

I was messing about with something like this that seemed to work but it kinda requires you to have a known list of keys.

let dataKeys = _.keys(pm.iterationData.toObject()),
    knownKeys = ['cz_citizenshipCode', 'cz_date', 'cz_visaInd', 'cz_type'],
    missingKeys = knownKeys.filter(key => !dataKeys.includes(key));

_.each(missingKeys, (item) => {
    pm.variables.set(item, "default_value")
}) 

I donโ€™t know how good that will be in your context as I know nothing about it.

You can also look at ways to dynamically construct your Request Body in the Pre-request Script and have more control over the way the data is handled.

@vdespa is always good at explaining these things so check out this video on his channel:

1 Like

Hi @danny-dainton,

Thank you so much! This is perfect! Now I only need to include the values I need in my data files (making them much smaller).

Again, many thanks :slight_smile:

Not the same behaviour, but I did an alternative version:

const defaultRgx = /(\{\{([\w_]*):?(\S*)\}\})/g;
const toPairs = (object) => _.keys(object).map((key) => [key, object[key]]);

// Process body to find variables
const rawBody = pm.request.body.toString();
const variables = rawBody.match(defaultRgx) || [];

// Extract defaults from default syntax
const defaults = {};
for (const variable of variables) {
  const [match, key, value] =
    variable.match(/\{\{([\w_]*):?(\S*)\}\}/) || [];
  if (match) {
    defaults[key] = value;
  }
}

// Update the body without default syntax
const newBody = rawBody.replace(defaultRgx, "{{$2}}");
pm.request.body = newBody;

// Filter not set variables
const sources = [ pm.environment, pm.collectionVariables, pm.globals, pm.iterationData ];
const filtered = _.filter(
  toPairs(defaults),
  ([key]) => !_.find(sources, (source) => source.has(key))
);

// Set the not found variables from the default
_.each(filtered, ([key, value]) => {
  pm.variables.set(key, value);
});

With this, you can use the format {{variable:default_value}}. The default value will be applied locally if the variable is unavailable at any level.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.