0
0
Postmantesting~15 mins

Why variables avoid hardcoding in Postman - Automation Benefits in Action

Choose your learning style9 modes available
Verify use of variables instead of hardcoded values in Postman request
Preconditions (2)
Step 1: Open the Postman collection
Step 2: Select the request that uses hardcoded URL and headers
Step 3: Replace the hardcoded URL with a variable {{baseUrl}}
Step 4: Replace the hardcoded header value with a variable {{authToken}}
Step 5: Set the variables baseUrl and authToken in the collection environment
Step 6: Send the request
Step 7: Verify the request uses the variable values from the environment
Step 8: Change the environment variable values
Step 9: Send the request again
Step 10: Verify the request uses the updated variable values
✅ Expected Result: The request should use the variable values from the environment instead of hardcoded values. Changing variables updates the request without editing the request itself.
Automation Requirements - Postman test scripts
Assertions Needed:
Verify request URL contains the environment variable value
Verify request headers contain the environment variable value
Verify response status is 200 OK
Best Practices:
Use environment variables for URLs and tokens
Avoid hardcoding values in requests
Use pm.environment.get() to access variables in scripts
Write assertions in the Tests tab
Automated Solution
Postman
pm.test('Request URL uses baseUrl variable', () => {
    const baseUrl = pm.environment.get('baseUrl');
    pm.expect(pm.request.url.toString()).to.include(baseUrl);
});

pm.test('Authorization header uses authToken variable', () => {
    const authToken = pm.environment.get('authToken');
    const authHeader = pm.request.headers.get('Authorization');
    pm.expect(authHeader).to.include(authToken);
});

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

This Postman test script checks three things:

  • That the request URL includes the baseUrl variable from the environment. This ensures no hardcoded URL is used.
  • That the Authorization header includes the authToken variable, avoiding hardcoded tokens.
  • That the response status code is 200, confirming the request succeeded.

Using pm.environment.get() accesses the current environment variables dynamically. This way, changing variables updates the request without editing the request itself, which is the main reason to avoid hardcoding.

Common Mistakes - 3 Pitfalls
Hardcoding URLs and tokens directly in the request
Not setting environment variables before running tests
Using global variables instead of environment variables for sensitive data
Bonus Challenge

Now add tests to verify that changing environment variables updates the request URL and headers dynamically

Show Hint