How To Use Variables Postman
Introduction to Postman Variables
Postman variables are a powerful feature that allows you to store and reuse values within your API requests and tests. This enables you to create flexible and dynamic tests that can adapt to different environments, scenarios, and data.
Why Use Postman Variables?
- Parameterization: Replace hardcoded values in your requests with variables, making your tests more maintainable and reusable.
- Environment Management: Store environment-specific settings (e.g., base URLs, API keys) in variables, allowing you to easily switch between different environments.
- Data Management: Create variables to store and retrieve test data dynamically, making your tests more robust.
- Dynamic Testing: Use variables to generate random data, timestamps, or other dynamic values to create realistic test scenarios.
Types of Postman Variables
Postman supports different types of variables:
1. Environment Variables:
Environment variables are scoped to a specific environment. This means that you can create different environments (e.g., “Development,” “Staging,” “Production”) and define environment-specific variables.
Example:
-
Define an environment named “Development” with variables:
baseUrl
with value “https://api.example.com/dev”apiKey
with value “your_dev_api_key”
-
Define another environment named “Production” with variables:
baseUrl
with value “https://api.example.com/prod”apiKey
with value “your_prod_api_key”
To Use Environment Variables:
- Open your Postman collection or request.
- Click on the “Environment” dropdown and select the desired environment.
- Access the environment variable within your request using the syntax
{{variable_name}}
, for example,{{baseUrl}}
.
2. Global Variables:
Global variables are accessible from any collection or request across all environments. They are ideal for storing commonly used values that remain consistent across environments.
Example:
- Define a global variable named
apiVersion
with value “v1”.
To Use Global Variables:
- Open the “Global Variables” tab in the Postman sidebar.
- Click “Add Variable” and define your global variable.
- Access the global variable using the syntax
{{variable_name}}
, for example,{{apiVersion}}
.
3. Data Variables:
Data variables allow you to store and iterate through a dataset within a collection. This is helpful when you want to test various data inputs within a single request.
Example:
- Define a data file named “users.json” with the following data:
[ { "name": "John Doe", "email": "john.doe@example.com" }, { "name": "Jane Doe", "email": "jane.doe@example.com" }]
- In your request, you can access individual data elements using the syntax
{{data['name']}}
and iterate through the dataset using a “Test” script.
To Use Data Variables:
- Click the “Data” tab in the Postman sidebar.
- Import or create a data file.
- In your request, access data items using
{{data['key']}}
.
How to Use Postman Variables in Requests
Postman variables can be used in various parts of your requests, including:
1. URL:
Replace hardcoded URL segments with variables:
Example Request:
GET {{baseUrl}}/users/{{userId}}
Explanation:
{{baseUrl}}
will be replaced with the value of thebaseUrl
environment variable.{{userId}}
will be replaced with the value of theuserId
variable (either another environment variable, global variable, or data variable).
2. Headers:
Substitute header values with variables:
Example Request:
Authorization: Bearer {{apiKey}}
Explanation:
{{apiKey}}
will be replaced with the value of theapiKey
environment variable.
3. Body:
Insert dynamic values in the request body:
Example Request Body (JSON):
{ "name": "{{userName}}", "email": "{{userEmail}}"}
Explanation:
{{userName}}
and{{userEmail}}
will be replaced with the values of the respective variables.
How to Manage Postman Variables
1. Define Variables:
You can define variables in the “Environment” tab, “Global Variables” tab, or through data files:
- Environment Variables: Click the “Environment” tab, select an existing environment or create a new one, and click “Add Variable.”
- Global Variables: Click the “Global Variables” tab, click “Add Variable.”
- Data Variables: Click the “Data” tab, import or create a data file.
2. Set Variable Values:
You can set the values of variables in different ways:
- Manually: Input the desired value in the “Value” field when defining the variable.
- Using Pre-Request Scripts: Use a pre-request script to dynamically set variable values.
- Using Tests: Set values within your test scripts using
pm.environment.set()
for environment variables,pm.globals.set()
for global variables, orpm.collectionVariables.set()
for collection variables.
3. Access Variables:
Use the {{variable_name}}
syntax to access variables within requests, pre-request scripts, and tests.
Sample Code Examples:
1. Using Environment Variables in a GET Request:
// Environment Variablespm.environment.set("baseUrl", "https://api.example.com/v1");pm.environment.set("userId", "123");
// Requestpm.sendRequest("{{baseUrl}}/users/{{userId}}", function (error, response) { if (error) { console.error("Error:", error); } else { console.log("Response:", response.text()); }});
2. Using Global Variables in a POST Request:
// Global Variablespm.globals.set("accessToken", "your_access_token");
// Request Bodyconst requestBody = { "name": "New User", "email": "newuser@example.com", "accessToken": "{{accessToken}}"};
// Requestpm.sendRequest({ url: "{{baseUrl}}/users", method: "POST", body: requestBody, headers: { "Content-Type": "application/json" }}, function (error, response) { // Handle response});
3. Using Data Variables in a Test:
[ { "name": "John Doe", "email": "john.doe@example.com" }, { "name": "Jane Doe", "email": "jane.doe@example.com" }]
// Test Scriptpm.test("Verify user data", function () { pm.expect(pm.response.text()).to.include(pm.data.name); pm.expect(pm.response.text()).to.include(pm.data.email);});
Conclusion:
Postman variables offer powerful capabilities for managing your API tests and enhancing their flexibility and reusability. By leveraging environment variables, global variables, and data variables, you can ensure your tests are readily adaptable to changing conditions, environments, and data inputs, resulting in more robust and efficient API testing practices.