0
0
Postmantesting~15 mins

Variable syntax ({{variable}}) in Postman - Build an Automation Script

Choose your learning style9 modes available
Verify usage of variable syntax {{variable}} in Postman request
Preconditions (2)
Step 1: Open the Postman collection
Step 2: Select the request that uses the URL with {{userId}} variable, e.g., https://api.example.com/users/{{userId}}
Step 3: Send the request
Step 4: Observe the request URL in the Postman console or request details
✅ Expected Result: The request URL should replace {{userId}} with the value '12345' from the environment variable, resulting in https://api.example.com/users/12345
Automation Requirements - Postman test scripts (JavaScript)
Assertions Needed:
Verify that the request URL contains the variable value '12345' instead of the literal '{{userId}}'
Verify the response status code is 200
Best Practices:
Use pm.environment.get('userId') to access variable values
Use pm.test() blocks for assertions
Avoid hardcoding variable values in tests; use environment variables
Log useful information with console.log for debugging
Automated Solution
Postman
pm.test('Request URL uses variable value', function () {
    const requestUrl = pm.request.url.toString();
    const userId = pm.environment.get('userId');
    pm.expect(requestUrl).to.include(userId);
    pm.expect(requestUrl).to.not.include('{{userId}}');
});

pm.test('Response status is 200', function () {
    pm.response.to.have.status(200);
});

The first test checks that the request URL contains the actual value of the environment variable 'userId' instead of the literal string '{{userId}}'. This confirms that Postman correctly replaced the variable syntax before sending the request.

The second test verifies that the response status code is 200, indicating the request was successful.

Using pm.environment.get('userId') ensures the test dynamically uses the variable value from the environment, making the test flexible and maintainable.

Assertions are wrapped in pm.test() blocks for clear reporting in Postman test results.

Common Mistakes - 3 Pitfalls
{'mistake': "Checking for the literal string '{{userId}}' in the request URL instead of the replaced value", 'why_bad': 'This does not verify that the variable was replaced; it only checks the raw template string.', 'correct_approach': "Check that the request URL contains the actual variable value from the environment and does not contain the literal '{{userId}}'."}
{'mistake': 'Hardcoding the variable value in the test instead of retrieving it from the environment', 'why_bad': 'Makes tests brittle and not reusable if the variable value changes.', 'correct_approach': "Use pm.environment.get('userId') to get the current value dynamically."}
Not verifying the response status code
Bonus Challenge

Now add data-driven testing with 3 different userId values to verify variable replacement and response success for each.

Show Hint