How To Use Variables In Postman
Using Variables in Postman for Efficient API Testing
Variables are essential for streamlining API testing in Postman, enabling you to reuse values, manage data dynamically, and write more flexible and maintainable tests. Let’s explore how to effectively leverage variables in your Postman workflows.
Defining Variables: The Foundation
There are several ways to define variables in Postman, each offering unique advantages:
1. Environment Variables:
- Purpose: Environment variables are ideal for storing configuration settings across different environments (e.g., development, testing, production).
- Example: You might have a base URL for your API that differs between environments.
- Declaration:
- Navigate to the Environments tab in Postman.
- Create a new environment or select an existing one.
- Add variables with their corresponding values, for example:
{"id": "development","values": [{"key": "baseUrl","value": "https://dev.example.com/api"}]}
2. Global Variables:
- Purpose: Global variables are accessible across all your Postman requests and collections.
- Example: You may want to store an API key or a common header value.
- Declaration:
- Go to the Globals tab in Postman.
- Add variables with their corresponding values:
{"id": "global","values": [{"key": "apiKey","value": "your_api_key"}]}
3. Collection Variables:
- Purpose: Collection variables are specific to a particular Postman collection, allowing you to manage data within the context of a set of requests.
- Example: You might store a user ID or a session token generated during previous requests within a collection.
- Declaration:
- Open your collection and click the ”…” button.
- Select “Edit”.
- Add variables in the “Variables” tab.
Accessing Variables in Requests
Postman provides several ways to utilize variables within your requests:
1. In Request URLs:
- Method: Use double curly braces
{{ }}
to reference a variable within your URL. - Example:
https://{{baseUrl}}/users
2. In Request Headers:
- Method: Use double curly braces
{{ }}
to refer to a variable within header values. - Example:
Authorization: Bearer {{apiKey}}
3. In Request Body:
- Method: You can use double curly braces
{{ }}
to incorporate variables within the request body. - Example:
{"name": "John Doe","email": "{{user_email}}"}
Dynamically Managing Variables: The Power of Scripts
Postman’s scripting capabilities enhance your ability to manipulate variables throughout the testing process.
1. Setting Variable Values in Pre-request Scripts:
- Method: Use
pm.environment.set()
,pm.globals.set()
, orpm.collectionVariables.set()
to define or update variable values before a request is sent. - Example:
pm.environment.set("userId", "12345");
2. Accessing Variable Values in Tests:
- Method: Use
pm.environment.get()
,pm.globals.get()
, orpm.collectionVariables.get()
to retrieve variable values within your test scripts. - Example:
const user_id = pm.environment.get("userId");pm.test("Check user ID", () => {pm.expect(user_id).to.be.equal("12345");});
3. Updating Variables in Tests:
- Method: Use
pm.environment.set()
,pm.globals.set()
, orpm.collectionVariables.set()
to update variables based on the response received. - Example:
pm.test("Get user data", () => {const response = pm.response.json();pm.environment.set("userName", response.name);});
Example Scenario: User Registration and Authentication
Let’s illustrate the practical application of variables in Postman with a common API testing scenario:
1. Define Variables:
Environment:
- Variable:
baseUrl
- Value:
https://api.example.com
Globals:
- Variable:
apiKey
- Value:
your_api_key
2. Create a Collection for User Registration and Authentication:
-
Request 1: Registration
- Method: POST
- URL:
{{baseUrl}}/users
- Headers:
Content-Type
: application/json
- Body (JSON):
{"username": "testuser","email": "{{user_email}}"}
- Pre-request Script:
// Generate a random email addresslet randomString = Math.random().toString(36).substring(2, 15);const user_email = `testuser-${randomString}@example.com`;pm.environment.set("user_email", user_email);
- Tests:
- Verify Success Status:
pm.test("Status code is 201", () => {pm.response.to.have.status(201);});
- Extract User ID:
pm.test("Response includes user ID", () => {const response = pm.response.json();pm.environment.set("userId", response.id);});
- Verify Success Status:
-
Request 2: Authentication
- Method: POST
- URL:
{{baseUrl}}/auth
- Headers:
Content-Type
: application/json
- Body (JSON):
{"username": "testuser","password": "testpassword"}
- Tests:
- Verify Success Status:
pm.test("Status code is 200", () => {pm.response.to.have.status(200);});
- Extract Auth Token:
pm.test("Response includes access token", () => {const response = pm.response.json();pm.environment.set("authToken", response.token);});
- Verify Success Status:
-
Request 3: Retrieve User Data (Using Auth Token)
- Method: GET
- URL:
{{baseUrl}}/users/{{userId}}
- Headers:
Authorization
: Bearer {{authToken}}
- Tests:
- Verify Success Status:
pm.test("Status code is 200", () => {pm.response.to.have.status(200);});
- Verify User Data:
pm.test("Response includes username", () => {const response = pm.response.json();pm.expect(response.username).to.be.equal("testuser");});
- Verify Success Status:
Benefits of Using Variables:
- Reusability: You can easily reuse variables across requests, reducing redundant data entry.
- Dynamic Data: Variables allow you to work with dynamic data like timestamps, random numbers, or data extracted from previous responses.
- Maintainability: Centralized variable management makes it easier to update values across multiple requests, ensuring consistency.
- Testability: Variables facilitate data-driven testing and enable you to build robust tests with complex scenarios.
Conclusion:
Variables in Postman empower you to perform more efficient, versatile, and well-organized API testing. By mastering the use of environment, global, and collection variables, and leveraging scripting capabilities, you can take your API testing to the next level, creating automated workflows and maximizing the effectiveness of your testing efforts.