Environment variables help you store and reuse values like URLs or tokens easily. They make tests simpler and faster to update.
0
0
Environment variables in Postman
Introduction
When you want to run the same test on different servers like development, testing, and production.
When you need to keep sensitive data like API keys safe and separate from your test scripts.
When you want to avoid repeating the same value in many places in your tests.
When you want to quickly change a value used in many requests without editing each one.
When you want to share common data across multiple requests or collections.
Syntax
Postman
pm.environment.set("variable_key", "value"); pm.environment.get("variable_key"); pm.environment.unset("variable_key");
Use pm.environment.set to create or update a variable.
Use pm.environment.get to read a variable's value.
Use pm.environment.unset to remove a variable.
Examples
Sets the environment variable
baseUrl to the API URL.Postman
pm.environment.set("baseUrl", "https://api.example.com");
Gets the value of the
authToken variable to use in a request.Postman
const token = pm.environment.get("authToken");Removes the variable
tempData from the environment.Postman
pm.environment.unset("tempData");Sample Program
This script sets an environment variable userId, retrieves it, prints it, and checks if it equals "12345".
Postman
// Set environment variable pm.environment.set("userId", "12345"); // Get and print environment variable const userId = pm.environment.get("userId"); console.log(`User ID is: ${userId}`); // Use environment variable in a test pm.test("User ID should be 12345", function () { pm.expect(userId).to.eql("12345"); });
OutputSuccess
Important Notes
Environment variables are case-sensitive.
Always clear variables you no longer need to avoid confusion.
You can manage environment variables in Postman's UI under the Environment quick look.
Summary
Environment variables store reusable values for your tests.
They help run tests easily on different setups without changing code.
Use Postman scripts to set, get, and remove these variables.