Understanding Variable Scopes And Environment Files In Postman

This Tutorial will Cover Different Types of Variables Supported by the Postman Tool and How They can be Used while Creating and Executing Postman Requests & Collections:

We will also touch upon the concept of environment files and see how they can be leveraged while creating and executing collections.

=> Check Out The Perfect Postman Training Guide Here.

Variable Scopes And Environment Files

What Are Variables In Postman?

Variables, like any other programming language, are nothing but placeholders to hold some value or result of some expressions.

For example, Consider a variable declaration in C#/Javascript that holds string value “hello world!”. Now whenever this string is required, someone can just use the name of the variable to get the value replaced as the actual string.

var z="hello world!"

Let’s try to dig deeper into variables in Postman.

Variables here are typically used in a context where you need to replace values in request bodies, make assertions for the response body and use them in pre-request scripts to handle pre-processing logic as required.

Firstly, let’s try to understand different variable scopes in Postman. Scope is nothing but the lifetime and accessibility of a variable. It’s similar to the concept of scope that we have in programming languages like Java.

For Example, a variable can have a global scope i.e. any class/method can access/modify the variable until the method or program is active.

Similarly, there can be various types that have a specific scope as local variables declared in the method can be used only till the time, that function is executing. Likewise, variables declared in for loops can only be used while that loop is executing.

Here is a Video Tutorial: 

Postman offers 5 different types of variable scopes as stated below:

  1. Global
  2. Collection
  3. Environment
  4. Data
  5. Local

Note: It’s important to understand that all the different types of Postman variables can be added/removed using the Postman console and most of them can be accessed and updated using scripts as well.

Let’s try to understand each of these variable types and scope in detail!!

Variable Types In Postman

#1) Global

What are Global Variables and when should they be used?

Global variables are general-purpose variables and should be mostly avoided and used only for quick prototyping requirements. These variables are available to all requests available in the Postman console, irrespective of what collection they belong to.

These variables are analogous to global scope variables in programming languages like Java, C#, etc., where the global variables are accessible to all parts of the program. However, these variables are highly unreliable as each section of code can access/modify the global variable value.

Working With Global Variables

To work with global variables, they can be controlled through the Postman console as well as the scripts in Postman requests.

Through the Postman console, click on the “Eye” icon near the environment selector, and that will open a popup/context window with details around the current global variables.

Global Vars Console

Now create a new variable by entering the variable name and its initial value.

The initial value is something that is persisted by default for that variable and the current value keeps changing as it is set or updated in the requests that are using these variables.

Set Global Vars Through Script

Using the script, environment variables can be accessed using “pm. globals”

Use the below command to get the value of a global variable named ‘testVar’.

pm.globals.get('testVar');

Use the below command to set the value of a global variable named ‘testVar’.

pm.globals.set('testVar', 'Hello Postman tutorial!');

If you want to remove a global variable through script, then you can use the unset function as mentioned below.

pm.globals.unset('testVar');

To clear all the global variables through the script, you can use the below function.

pm.globals.clear();

#2) Collection

What are Collection Variables and when should they be used?

Collection variables are used to define variables at the collection scope. As we know, a collection in Postman is nothing but a group of Postman requests.

Collection variables do not change during the execution of a collection or request inside the given collection. Essentially Collection variables could be just retrieved and not updated during request execution.

Please note, that the collection variables could be accessed just by the requests that are a part of the collection and not be any other requests.

How Are They Created?

Collection variables can be created and/or removed only using the Postman application console.

#1) Select the collection where you want to add a variable. Right click and select edit.

Collection Edit Menu

#2) Now select the “Variables” tab and add the collection variables that are required to be added.

Add Collection Variables

Working With Collection Variables

For using inside a request, collection variables can be referred using generic Postman script and depending upon the rule of closest scope, if there is no other variable which is closer than the collection scope, then the collection variable gets returned.

pm.variables.get('testCollectionVar');

To use Postman variables as a part of the request builder, simply use the double curly brace syntax as shown below.

Collection Variables Request Builder

#3) Environment

What are the Environment Variables?

Environment variables are the most heavily used kind of variables in Postman.

They are tied to a selected environment that’s being used for executing the request. They have a narrower scope than the Global variables but broader than the Collection variables.

When To Use the Environment Variables?

  1. Environment variables are ideal when working with different servers. For example, generally, while working on a project you work with a lot of different environments like dev, test, stage, and prod, etc which differ mostly just by URL and the rest of the things in the API endpoint request URL remain the same.
    In this kind of scenario, you can create an environment file matching the different environments that your application supports. For example, environment variables for different environments like dev, test, etc.
  2. When there is a need for passing data or information from one request to another, environment variables are a good choice, as they have a broader scope than the Local variables and narrower scope than Global variables.

How Are They Created?

Unlike Collection variables, Environment variables can be created both through the console as well as through the script itself.

For creating environment variables through the console, an active environment needs to be created which is nothing but a container of environment variables. Please refer to the screenshots below to create a new environment and add environment variables to it.

View Environment Variables

Now you can click “Add” to save the new environment. Once saved, you can simply click the “Settings” icon to manage/add new environments.

Manage Environments

In order to use the created environment, you will need to choose the environment to use, by selecting the right environment from the environment list dropdown.

Environment Selector

Working With Environment Variables

Similar to the Collection & Global variables, Environment variables can be acted upon programmatically through the script and can be used directly as a part of the URLs or request body through double curly braces syntax.

When an appropriate environment is selected in the environment selector, you can simply use the double curly brace syntax to access an Environment variable as depicted in the below screenshot.

Select Environment Variable

In order to use Environment variables through the script, you can use pm.environment.get and pm.environment.set to fetch and add/modify environment variables respectively.

pm.environment.get('testEnvVar')
pm.environment.set('testEnvVar',10)

Please note that here, we are using pm.environment and not pm.variables i.e. the scope is always set to the environment and Postman will try to find out the variable only in the selected environment.

#4) Local

What are Local Variables?

Local variables are available only within the context of particular request execution. This is in analogy to function level variables in modern programming languages like Java and C#. These are exactly similar to Function variables in which the variables just have access within the context of the function execution.

One important use case of local variables is that they can be used when you want to override the values of a variable that is defined in any other scope like Global, Collection or Environment.

i.e. Suppose there’s a global variable named ‘testVar’ and now you want to override the value without affecting the Global variable, you can create a local variable with the same name and use it with the value you like.

When to Use the Local Variables?

Local variables can be used in the same way as Collection, Global and Environment variables that we discussed in the earlier sections of this tutorial.

It’s important to note here that, to use the Local variables programmatically, you have to use pm.variables.get / pm.variables.set unlike pm.environment or pm.global which was used for the Environment and Global variables.

pm.variables.get('testVar')
pm.variables.set('testEnvVar',10)

#5) Data

What Are Data Variables?

Data variables come in the context of request execution through the collection runner.

Postman allows us to execute requests in a collection through the collection runner and while execution we can provide a data set in the form of JSON or CSV that are used while running the requests inside the collection.

It’s important to note here that the source of Data variables is the user-supplied data file in the format of JSON or CSV, and during the request execution, the Data variables can only be fetched but not updated/modified or added.

When To Use Data Variables?

Data variables are used while we are working with multiple data-sets and they exist only during the execution of an iteration from the data file.

How To Use a Data Variable?

Let’s see an end to end scenario of executing requests through collection runner and supplying a data file whose value is replaced while the request is getting executed.

Let’s add a simple GET request to a new collection to illustrate the concept of Data variables. We will use the same GET endpoint https://reqres.in/api/users/{userId}

We will be fetching the {userId} through a Data variable which will be backed by a CSV file containing the values for the userId.

Please follow the below steps to understand the flow.

#1) Change the request URL in the Postman request builder to https://reqres.in/api/users/{{testDataVar}}.

Data Variables

#2) Here, {{testDataVar}} is our data variable whose value will be fetched from the data source that will be used with the collection runner.

#3) Create a new data file in CSV format with the column name as “testDataVar”.

Set the data in the CSV file as below:

testDataVar
1
2
3
4
5

#4) Save the file onto the local file system and use this file while running the collection through the collection runner.

#5) Now select the collection and click Run to execute the collection requests through the collection runner.

Collection Runner

#6) Select the created csv data file in the collection runner configuration and the file type as text/csv.

Variable Option Selection

#7) Now hit “Run Postman collection” and refer to the “Run Results” window. There’s an execution detail for the configured request for each iteration that was performed. The number of iterations depends upon the number of data inputs that were configured in the CSV file.

Collection Runner Results

You can see more details about the request URLs etc., in the collection runner results, to validate if the values of the Data variables were passed correctly to the request URLs. Generally, Data variables are used when the collection requests are to be executed against multiple data sets as per the configured values in the data files.

Accessing Postman Variables

Postman variables can be accessed in 2 ways as stated below.

  1. In the request, builder variables can be accessed using a double curly brace format. Please note that while resolving the variable, the closest scope variable value will be replaced before the request gets executed.
  2. In the script, like the pre-request script, tests, assertions, etc the variables can be accessed/modified using the below syntax.

To fetch a Variable:

pm.variables.get(‘variable-name’)

To set a Variable value.

pm.variables.set(‘variable-name’,’variable-value’)

It’s important to note here, that when a variable is set, it will try to find the closest scope variable and set or modify that variable. In case, there is no variable found during the set, the Postman script will simply create a new Local variable.

Notes And Tips

#1) It is advisable to have different variable names in different scopes, to avoid confusion as Postman sandbox will choose the variable with the closest scope when it tries to resolve variables in the request builder with double curly brace format or when the pm.variables.get / pm.variables.set script is resolved.

#2) For Environment variables, only the selected environment is effective i.e. while resolving the variables, Postman will just look into the selected environment only.

#3) Please note a general rule of thumb – A variable with the closest scope is given precedence over others. For example, if there is a global variable named ‘input1’ and there’s a local variable with the same name and if the variable is referenced in the scope of a local variable, then the variable in the local scope has more precedence when compared to the global variable.

Conclusion

In this tutorial, we touched upon a lot of concepts related to variables in Postman along with the different ways to use them. We discussed the types of variables like Global, Collection, Environment, Local & Data and when to use each of them.

In a nutshell, Postman variables add a lot of power to the way in which the tool can be used and configured for executing requests and tests in an effective way. Few references from the Postman official documentation could be obtained here.

=> Visit Here To See A-Z Of Postman Training Tutorials Here.