0
0
Postmantesting~15 mins

Response headers in Postman - Build an Automation Script

Choose your learning style9 modes available
Verify response headers for a GET request
Preconditions (2)
Step 1: Open Postman
Step 2: Create a new GET request to https://api.example.com/data
Step 3: Send the request
Step 4: Check the response headers section
✅ Expected Result: The response headers include 'Content-Type' with value 'application/json' and 'Cache-Control' with value 'no-cache'
Automation Requirements - Postman test scripts
Assertions Needed:
Verify 'Content-Type' header exists and equals 'application/json'
Verify 'Cache-Control' header exists and equals 'no-cache'
Best Practices:
Use pm.response.headers.get() to access headers
Use strict equality checks for header values
Write clear and descriptive assertion messages
Automated Solution
Postman
pm.test('Content-Type header is application/json', () => {
    const contentType = pm.response.headers.get('Content-Type');
    pm.expect(contentType).to.eql('application/json');
});

pm.test('Cache-Control header is no-cache', () => {
    const cacheControl = pm.response.headers.get('Cache-Control');
    pm.expect(cacheControl).to.eql('no-cache');
});

The first test checks if the 'Content-Type' header is exactly 'application/json'. We use pm.response.headers.get() to get the header value and pm.expect().to.eql() for strict equality.

The second test does the same for the 'Cache-Control' header, verifying it equals 'no-cache'.

This approach ensures the headers are present and have the expected values, which is important for API correctness.

Common Mistakes - 3 Pitfalls
{'mistake': "Using pm.response.headers['Content-Type'] instead of pm.response.headers.get()", 'why_bad': 'pm.response.headers is not a plain object, so direct property access returns undefined.', 'correct_approach': "Use pm.response.headers.get('Content-Type') to correctly retrieve header values."}
Using loose equality (==) instead of strict equality (=== or to.eql()) in assertions
Not checking if the header exists before asserting its value
Bonus Challenge

Now add data-driven testing with 3 different API endpoints and verify their 'Content-Type' headers

Show Hint