In modern application development, Web API is an important part of an application. It helps develop various applications on different platforms with the same back-end logic, such as - in a banking application, we get the same options in the Internet Banking (Website) and Mobile Banking (app) with their same functionality on different application platforms.
In this article, we will learn how to store values in environment variables and how to use them.
Prerequisites
- Install the Postman tool and sign in with your Google account.
Signing in is required to store the environment data in Postman.
- Web API application details (URL, Credentials, User guide).
Here, I am using my own Web API developed in C# and it has OAuth 2.0 authentication method.
Practical
- Run the POSTMAN tool and log in using the Google account.
- Create an environment to hold the data required for testing, using the Setting -> Manage Environments option.
- Click on the "Add" button under the "Manage Environment" tab.
Then, give the environment name as “Localhost” and add one key “URL” with Value “http://localhost:49367/” (This is the base URL of our Web API). Now, click the "Add" button to save this environment.
- Now, change the environment using the options shown in the below screenshot. Select “Localhost” environment from the drop-down.
- Now, select POST method to get the token from Web API.
- We need to access the environment variable “URL”. You can access any environment variable using the {{<variable name>}} symbol.
Then, append “/token” string in the URL, as shown below.
- Set the header “Content-Type” with value “application/x-www-form-urlencoded”.
- Set the pre-request script to create the environment variables with given values.
Syntax
- postman.setEnvironmentVariable("<key>", "<value>");
- postman.setEnvironmentVariable("username", "vivek");
- postman.setEnvironmentVariable("password", "pass");
- postman.setEnvironmentVariable("grant_type", "password");
This will create the environment variables.
- Now, send these variable values in the request. Add the below statement in the request row body and click on the "Send" button to receive the token.
- username={{username}}&password={{password}}&grant_type={{grant_type}}
- In the above step, we are getting the token from Web API.
Now, we will read the token value from response and store in the environment variable using the below statement written in the "Tests" tab. This tab executes the scripts after calling the Web API.
- var jsonData = JSON.parse(responseBody);
- postman.setEnvironmentVariable("access_token", jsonData.access_token);
- Now, click the "Send" button.
- After calling the Web API, check the list of all environment variables created at runtime. (Go to Settings-> Manage Environments-> click on your environment name,i.e., “Localhost”)..
In the next article, we will see some more techniques to test the data using Postman automation.