Set Environment variables based on collection names?

I have several different Environment variables names, each in a specific format. For example TESTvar1, DEVvar1, SANDBOXvar1…where the collection names are TEST, DEV, and SANDBOX, respectively.

I would like to build a standard template for a collection, and clone it, based on the name of the collection, so that it refers to the correct environment variable, something like {{(collection name)var1}} .

How can I accomplish this?

Certainly @louism3! The feature you’re referring to isn’t built directly into Postman. However, you can implement a workflow that accomplishes this using pre-request scripts in combination with Postman’s scripting capabilities.

Here’s a suggested approach:

  1. Use Collection-Level Pre-request Script: Start by adding a pre-request script at the collection level. This script will execute before any request within that collection.
  2. Retrieve Collection Name: In the pre-request script, get the collection name using
  3. Construct the Environment Variable Name: Concatenate the collection name with the desired suffix to form the variable name. For instance, if your collection name is TEST, you’ll form the variable name as TESTvar1.
  4. Access the Environment Variable: Use pm.environment.get(variableName) to retrieve the value of the constructed environment variable.

Here’s an example of what this may look like as a pre-request script:

// Get collection name
let collectionName =;

// Construct the environment variable name
let variableName = collectionName + "var1";

// Get the value from the constructed variable name
let variableValue = pm.environment.get(variableName);

// You can now use this value as needed
  1. Usage in Requests: In the actual API requests within your collection, you won’t reference the environment variables with the typical {{varName}} format. Instead, you’ll leverage the constructed variable name from the pre-request script.
  2. Cloning the Collection: Whenever you clone the collection and rename it to, let’s say, DEV, the pre-request script will automatically reference DEVvar1 due to the dynamic construction of the environment variable name.

Remember, for this to work seamlessly, ensure the environment variables (TESTvar1, DEVvar1, SANDBOXvar1, etc.) are properly set up in your chosen environment in Postman.

This approach provides a dynamic way to reference environment variables based on collection names, reducing manual changes and errors when cloning or reusing collections. Hope this helps! :slight_smile:

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