0
0
Postmantesting~15 mins

Environment variables in Postman - Build an Automation Script

Choose your learning style9 modes available
Verify usage of environment variables in Postman request
Preconditions (2)
Step 1: Select the environment 'TestEnv' in Postman
Step 2: Create a new GET request with URL '{{baseUrl}}/posts/1'
Step 3: Send the request
Step 4: Observe the response status code and body
✅ Expected Result: The request is sent to 'https://jsonplaceholder.typicode.com/posts/1' and the response status code is 200 with a valid JSON body containing post details
Automation Requirements - Postman/Newman
Assertions Needed:
Verify response status code is 200
Verify response body contains userId, id, title, and body fields
Best Practices:
Use environment variables for base URLs and dynamic data
Use pm.expect assertions for validation
Keep tests independent and clear
Automated Solution
Postman
pm.test('Status code is 200', () => {
    pm.response.to.have.status(200);
});

const jsonData = pm.response.json();
pm.test('Response has userId', () => {
    pm.expect(jsonData).to.have.property('userId');
});
pm.test('Response has id', () => {
    pm.expect(jsonData).to.have.property('id');
});
pm.test('Response has title', () => {
    pm.expect(jsonData).to.have.property('title');
});
pm.test('Response has body', () => {
    pm.expect(jsonData).to.have.property('body');
});

This script is written in Postman test tab using pm API.

First, it checks if the response status code is 200, meaning the request was successful.

Then, it parses the response JSON and verifies that the expected fields userId, id, title, and body exist in the response.

Using environment variable {{baseUrl}} in the request URL allows easy switching of target servers without changing the test code.

Common Mistakes - 3 Pitfalls
Hardcoding the full URL instead of using environment variables
Not checking the response status code before validating response body
Using incorrect syntax for pm.expect assertions
Bonus Challenge

Now add data-driven testing by running the same request with environment variables for post IDs 1, 2, and 3

Show Hint