Collection runner variable scope

I am attempting to create a data driven request that has default values defined as variables at the collection level. So, if the request is manually sent the default variables are used, but if the collection runner and a data file are used, the default values are overwritten and replaced with new values from the data file, like so:

Request:

Default values defined as variables at the collection level:

Sending the request uses the default values, as you’d expect.

I then created a data file with exactly the same variables represented as columns:

Again, when using the Collection runner, these variables from the data are used as expected.

My question is regarding variable scope. **If I don’t specify one or more variables in the data file and simply leave them blank, can I have these populate from the default collection variables? **

Where do collection runner variables fall in the scope hierarchy and how do they relate to variables defined in a data file?

This is what I’ve found in a post by @singhsivcan:

1. Global (Lowest)
2. Collection (Read-only)
3. Environment
4. Data
5. Local (Highest)

I feel like you’ve already answered your own question.

Here is the documentation on variable scoping.

If a variable is defined in a specific scope, but has no value - it is still going to return a blank value. So if your data variable is blank, you’ll get a blank.

One way you could get around this is to coalesce the values in a pre-request script.

let myVariable = pm.iterationData.get("variable_name");
if(!myVariable) {
  myVariable = pm.collectionVariables.get("variable_name");
}

pm.variables.set("variable_name", myVariable);

This will set either the data variable or the collection variable to a local variable, which has the highest priority.

1 Like

Thanks Allen - your answer regarding coalescing the values is exactly what I was after. I could work my head around the variable scopes, but not how to use one or the other depending on that scope.

Thanks for your help.

1 Like

Any time, happy to help!