Postman Dynamic Variables
Postman’s dynamic variables are powerful tools to help developers perform API testing with less effort. They provide flexible ways to inject and manage data directly into requests and scripts. They can be configured in the folder, environment, or even in a single request. They promote consistency and also by simplifying repetitive tasks they save a lot of time.
Table of Content
- Types of Dynamic Variables
- Step By Step Working with Dynamic Variables
- Examples of Postman Dynamic Variables
- Advanced Techniques and Tips
- Troubleshooting Dynamic Variables
- Conclusion
Prerequisites
This article requires the user to have some basic experience with Postman in making API requests. If not, just download Postman and give it a try; it is easy to interpret. Once you are comfortable with the options available in the tool and can hit a couple of APIs, kindly follow along.
Types of Dynamic Variables
Predefined Variables
As the name says these are predefined; ready to use. They are categorized based on their domain of usage and relevance.
1. Common:
Variable Name | Description |
Examples |
---|---|---|
$randomUUID |
It generates a random 36-character UUID. UUID is a Universal Unique Identifier that is used as a unique ID when saving data to databases and fetching them in O(1). Although it can be used for many applications it is most widely used as a Primary key for entities. |
8f010747-d22d-4f28-a4c0-2f44cabb5510, f2a3c8b3-6f08-40ed-854e-fce241781a5a |
$timestamp |
It returns the current UNIX timestamp in seconds since Epoch. Epoch is a popular and most widely used convention for computers to track time; here a fixed time called “Thursday 1st January 1970” is used as a reference to measure the time that has passed since then. For example, when you use this variable in the year 2024 it looks something like this 1704535541; this tells how many years, months, days, hours, minutes, seconds, and milli-seconds have passed after the Epoch. |
1704538732, 1704538740 |
2. Numbers, Texts and Colors:
Variable Name | Description |
Examples |
---|---|---|
$randomAlphaNumeric |
It returns a random alpha-numeric number. Any character from a-z and 0-9 can appear when you use this random variable. |
0, ‘0’, ‘e’,1,5 |
$randomHexColor |
It returns a random hex color code. The values are a special code that represents color values from 0 to 255, used in HTML, CSS, and SVG. Each hex code refers to a specific color, allowing designers and developers to communicate about the exact color they are referring to. |
#451e02, #6f3a2c |
$randomBoolean |
It returns either true or false. It is as simple as it sounds. If you want to explore how these work behind the scenes checkout Fakerjs npm package. They have detailed documentation available as to how to use additional options. |
true, false |
$randomInt |
It returns a random integer value between 0 and 1000. A fun use case would be to randomly assign a number to each participant in a lucky draw; beware of this returning a 0 to any customer. |
884, 183, 93 |
$randomAbbreviation |
It generates a random abbreviation. |
SCSI, JSON, COM, SMTP, GB, SSL, HTTP, RAM |
$randomColor |
It returns a random color in the text format. When you are playing Ludo, this could be useful to randomly assign colors so that Sheldon doesn’t take green color every time. (A Big Bang theory reference) |
sky blue, green, cyan, lime, tan |
3. Address, Location, Phone:
Variable Name | Description |
Examples |
---|---|---|
$randomPhoneNumber |
It returns a random 10-digit phone number. |
273-439-9587, 381-481-1518, 681-920-9004 |
$randomStreetAddress |
It returns a random street address |
8632 Thomas Port, 536 Schinner Flats, 510 Waters Harbor |
$randomCity |
It returns a city name at random. You can use this when you have to make a small talk with strangers for the question where are you from. |
St. Paul, Berwyn, Victormouth, New Carmelo. |
$randomLatitude |
It returns a random latitude coordinate. |
32.9050, 56.8508, -74.5084 |
4. Names:
Variable Name | Description |
Examples |
---|---|---|
$randomFirstName |
It returns a random first name. |
Gerson, Dominique, Bessie, Alejandra |
$randomLastName |
It returns a random last name. |
Quitzon, Auer, Maggio, Ferry |
$randomNamePrefix |
It returns a random name prefix. |
Dr., Mr., Miss, Ms, Mrs. |
5. Dates:
Variable Name | Description |
Examples |
---|---|---|
$randomDateFuture |
It returns random future datetime. |
Wed Jun 05 2024 16:07:00 GMT+0530 (India Standard Time), Sat Dec 28 2024 09:06:20 GMT+0530 (India Standard Time) |
$randomDateRecent |
It returns a recent datetime randomly. |
Sat Jan 06 2024 07:36:55 GMT+0530 (India Standard Time), Sat Jan 06 2024 17:10:17 GMT+0530 (India Standard Time) |
$randomMonth |
It returns a random month. |
April, February, June |
$randomWeekday |
It returns a random weekday |
Wednesday, Friday, Sunday |
6. Databases:
Variable Name | Description |
Examples |
---|---|---|
$randomDatabaseColumn |
It returns a random database column name |
comment, status, category, updatedAt |
$randomDatabaseType |
It returns any random data type that is usually stored in databases. |
smallestPostgreSQL(used in SQL and MYSQL), binary(all databases), geometry(SQL), serial(postgresql), point(PostgreSQLreturns) |
$randomDatabaseEngine |
It returns a random database engine. |
InnoDB, MyISAM, MEMORY, BLACKHOLE |
7. Domains, Username, and Emails:
Variable Name | Description |
Examples |
---|---|---|
$randomDomainName |
It returns a random domain name |
shawn.net, lafayette.biz, alaina.com, kamille.biz |
$randomEmail |
It returns a random email address. |
John.Batz@hotmail.com, Jamar_Ritchie@hotmail.com, Clint6@gmail.com |
$randomDomainWord |
It returns a random unqualified domain name. An unqualified domain name is a domain name that doesn’t have any dots. For example, “www” is an unqualified domain name. |
Examples: immanuel, lisandro, edwin |
$randomUserName |
It returns a random username. |
Noelia27, Carolina.Okuneva, Florencio30 |
8. Internet and IP Address:
Variable Name | Description |
Examples |
---|---|---|
$randomProtocol |
It returns a random internet protocol. It returns either http or https. |
HTTP, HTTPS |
$randomIP |
It returns a random IPv4 address. |
28.93.163.70, 68.45.188.68, 222.74.133.238 |
$randomIPV6 |
It returns a random IPv6 address. |
8c97:5a4a:3e83:c026:c06d:95c5:3003:99d9, cbd2:fadc:15a8:665f:457b:04d1:825a:6275 |
9. Files and Directories:
Variable Name | Description |
Examples |
---|---|---|
$randomFileName |
It returns a random file name; watch out for the uncommon extensions |
cross_platform_mesh_blockchains.ogx, coordinator.qxl, assistant_withdrawal.cxx |
$randomFileType |
It returns a random file type |
application, image, message, audio, message |
$randomDirectoryPath |
It returns a directory path |
/var/tmp, /usr/local/bin, /boot/defaults |
10. Images:
Variable Name | Description |
Examples |
---|---|---|
$randomImageDataUri |
It returns a random data image URI. |
data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20version%3D%221.1%22%20baseProfile%3D%22full%22%20width%3D%22undefined%22%20height%3D%22undefined%22%3E%3Crect%20width%3D%22100%25%22%20height%3D%22100%25%22%20fill%3D%22grey%22%2F%3E%3Ctext%20x%3D%22NaN%22%20y%3D%22NaN%22%20font-size%3D%2220%22%20alignment-baseline%3D%22middle%22%20text-anchor%3D%22middle%22%20fill%3D%22white%22%3Eundefinedxundefined%3C%2Ftext%3E%3C%2Fsvg%3E |
11. Business:
Variable Name | Description |
Examples |
---|---|---|
$randomCompanyName |
It returns a random company name |
Mayer – Konopelski, Hahn, Haag and Hand, Kuhlman Group |
$randomBs |
It returns a random business speak; some buzzwords usedthe in the corporate world. |
morph front-end deliverables, harness B2B e-business, deliver extensible infomediaries |
$randomCompanySuffix |
It returns a random company suffix |
Group, LLC, Inc |
12. Finance:
Variable Name | Description |
Examples |
---|---|---|
$randomBankAccount |
It returns a random 8-digit bank account number. |
93838670, 18456375 |
$randomBankAccountName |
It returns a bank account name |
Investment Account, Auto Loan Account, Checking Account |
$randomCreditCardMask |
It returns a random masked credit card number |
2499, 6875, 1448 |
Note:
The examples are referred from official Postman documentation to be more accurate and Postman uses a library called Faker.js for random data generation.
Environment Variables
Defined within environments and scoped to requests within that environment.
- DEV_AWS_API_KEY: Store your API key of the URLDEV environment.
- LOCAL_BE_URL: Dynamically adjust the base URL for local, QA.
Collection Variables
Shared across all requests within a collection.
- PRODUCT_ID: Specify the product ID for testing with different products.
- AUTH_SERVICE_URL: Auth service URLand to be used in the collection.
Global Variables
Defined once and accessible from all environments and collections.
- COMPANY_NAME: Use your company name consistently across all tests.
Step By Step Working with Dynamic Variables
Step 1: Setup Node App
Open VScode and type the following command. Remember to create a separate folder for this project, and to name it like Postman_Dynamic_Variables so that you can check it whenever you need in the future. Navigate to the installsPostman_Dynamic_Variables folder.
touch index.js
This creates a new file with the name index.js in the current folder. Open terminal and type:
npm i express nodemon
This installs, express and nodemon packages, express helps us to create APIs and work with them and nodemon helps us to run the app with hot-reload capability. Make sure you are connected to the internet.
Upon successful run,, this command creates a folder node_modules, package.json and package-lock.json in the current directory. This is expected; now follow along and run in the terminal:
npm init -y
Now open the the index.js file and paste the following code; here we have written a sample express app with a plain POST route.
Step 2: Write the Core App Logic
index.js
Node
const app = express();
app.post(‘/’, (req, res) => {
res.send(‘Hello, welcome to my Express app!’);
});
const port = 8080;
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Now open package.json and paste the following line under the the scripts section:
“start”: “nodemon index.js”
Now your package.json should look like this:
Node
"dependencies": {
"express": "^4.18.2",
"nodemon": "^3.0.2"
},
"name": "pdv",
"version": "1.0.0",
"main": "index.js",
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": ""
}
Step 3: Run the App
Now open a terminal and type:
npm run start
You should be able to see something like this:
To check if your app is accessible from Postman, open a new tab and type the following URL, you should be seeing Hello, welcome to my Express app!
http://127.0.0.1:8080/
Note:
127.0.0.1 is the shownsame as localhost and remember the method type is POST.
Step 4: Write the API to Serve Requests
Now we will modify our index.js file to store the employee details temporarily in the server’s RAM as shownlet’s below:
Node
const app = express();
app.use(express.json());
let employeeDetails = {};
// uniqueId – $guid
// createdAt – $timestamp
// defaultPassword – $randomPassword
// firstName – $randomFirstName
// lastName – $randomLastName
// prefix – $randomNamePrefix
// location – $randomJobArea
// designation – $randomJobTitle
// responsibilities – $randomJobDescriptor
// contact – $randomPhoneNumber
// city – $randomCity
// country – $randomCountry
// profile – $randomPeopleImage
// catchPhrase – $randomCatchPhrase
// joinedOn – $randomDateRecent
// email – $randomEmail
// department – $randomDepartment
// bio – $randomLoremText
app.post(‘/’, (req, res) => {
try {
const tempEmployeeDetails = req.body.employeeDetails;
console.log("tempEmployeeDetails >>>>", tempEmployeeDetails);
if (tempEmployeeDetails) {
employeeDetails[tempEmployeeDetails["uniqueId"]] = {
…tempEmployeeDetails,
}
res.send(employeeDetails);
}
} catch (error) {
console.error("Error occurred in processing your request", error);
res.send(‘BAD REQUEST!!’);
}
});
const port = 8080;
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Step 5: Hit the API and Save Data
Now let’spostman’s try to hit this router and see if the details are being saved successfully or not.
The following is the postman’san body:
Javascript
{ "employeeDetails" : { "uniqueId" : "{{$guid}}" , "createdAt" : "{{$timestamp}}" , "defaultPassword" : "{{$randomPassword}}" , "firstName" : "{{$randomFirstName}}" , "lastName" : "{{$randomLastName}}" , "prefix" : "{{$randomNamePrefix}}" , "location" : "{{$randomJobArea}}" , "designation" : "{{$randomJobTitle}}" , "responsibilities" : "{{$randomJobDescriptor}}" , "contact" : "{{$randomPhoneNumber}}" , "city" : "{{$randomCity}}" , "country" : "{{$randomCountry}}" , "profile" : "{{$randomPeopleImage}}" , "catchPhrase" : "{{$randomCatchPhrase}}" , "joinedOn" : "{{$randomDateRecent}}" , "email" : "{{$randomEmail}}" , "department" : "{{$randomDepartment}}" , "bio" : "{{$randomLoremText}}" } } |
Output:
Examples of Postman Dynamic Variables
I am sure you all know what a variable is, as shown in the below good old C++ example; it is a symbolic name associated with a value that can be changed.
variable.cpp
C++
#include <iostream> using namespace std; int main() { int num; num = 4; cout << "Before changing the Number is:" << num << endl; num = 14; cout << "After changing the Number is:" << num << endl; return 0; } |
Output:
Before changing the Number is:4
After changing the Number is:14
Here the value of num can be changed as and when needed; dynamically. Then what does Dynamic variable mean?
Let’s say you are working on an Employee Management Application, you want to create an account for all the employees who have joined your organisation with a default dummy password. But you don’t have to handle the hassle of generating a stronger passwords; instead you can use $randomPassword when you are saving that user details.
Example 1:
Copy and paste this code in the body of a POST request in Postman new window, and then click on the code snippet icon on the right. This shows the request data that will be sent to the API.
Javascript
{ "name" : "Akanksha" , "department" : "Engineering" , "password" : "{{$randomPassword}}" , "shouldResetPassword" : true , "employeeId" : "EMP-896" } |
Example 2:
Javascript
{ "name" : "Bindu Kumari" , "department" : "Operaions" , "password" : "{{$randomPassword}}" , "shouldResetPassword" : true , "employeeId" : "EMP-990" } |
Paste this code in Postman’s new window and click on the code snippet icon to see the data that will be sent to the API in the request.
If you take a close look at this example we have used the $randomPassword enclosed in {{ }}.
{{$dynamic_variable_name}}
This is the right syntax to use a Dynamic variable in PostmanPostman. Here we got two different values for the field password for two requests. Hence the name Dynamic. It can pass different values to the field each time a request is made.
Note:
Random default password is demonstrated here just for reference and not to encourage to use this for real world applications. Depending on the use case and app flow a strong authentication flow is usually setup; this includes not storing the passwords in the app or database in plain text.
Advanced Techniques and Tips
- Combine variables: Create complex values by joining multiple variables: `{{$firstName}} {{$lastName}}`.
- Conditional dynamic values: Utilize pre-request scripts to set variable values based on conditions. Access and manipulate variables using Postman scripting language (`pm.environment.get(“API_KEY”)`)
- Dynamic tests: Inject dynamic values into test assertions for flexible validation.
- Share variables with team members: Collaborate on test suites by sharing environment and collection variables.
Troubleshooting Dynamic Variables
- Ensure correct syntax: Double-check curly braces and variable names.
- Variable scope: Use the correct scope for the variable you want to access.
- Environment selection: Dynamic values might not be updated if the wrong environment is chosen.
- Debug scripts: Utilise the console to diagnose errors in pre-request or test scripts.
Conclusion
Postman dynamic variables are an invaluable tool for streamlining your API testing workflow. Here we have used various Dynamic Variables provided by Postman for different requirements, the variable names are considered in such a way that all the fields are self-explanatory. feel free to check their official documentation for more useful variables and comment here if any queries or suggestions.