How to Assert Response Header in Postman Tests
In Postman, you can assert response headers using the
pm.response.headers.get('Header-Name') method inside the Tests tab. Use pm.expect() to write assertions, for example, pm.expect(pm.response.headers.get('Content-Type')).to.equal('application/json') to verify a header value.Syntax
Use pm.response.headers.get('Header-Name') to get the value of a specific response header. Then use pm.expect() to assert its value.
pm.response.headers.get('Header-Name'): Retrieves the value of the header named 'Header-Name'.pm.expect(value).to.equal(expectedValue): Checks if the actual header value matches the expected value.
javascript
pm.test('Check Content-Type header', () => { const contentType = pm.response.headers.get('Content-Type'); pm.expect(contentType).to.equal('application/json'); });
Example
This example shows how to assert that the Content-Type header is application/json and the Cache-Control header contains no-cache.
javascript
pm.test('Validate response headers', () => { const contentType = pm.response.headers.get('Content-Type'); const cacheControl = pm.response.headers.get('Cache-Control'); pm.expect(contentType).to.equal('application/json'); pm.expect(cacheControl).to.include('no-cache'); });
Output
PASS Validate response headers
Common Pitfalls
Common mistakes when asserting response headers in Postman include:
- Using incorrect header names (header names are case-insensitive but must be exact strings).
- Not checking if the header exists before asserting, which can cause errors if the header is missing.
- Using
pm.response.headers.get()incorrectly by passing an undefined or empty string.
Always verify the header name and consider adding a check for header presence.
javascript
pm.test('Check header exists before asserting', () => { const headerName = 'X-Custom-Header'; const headerValue = pm.response.headers.get(headerName); pm.expect(headerValue, `${headerName} should be present`).to.not.be.undefined; pm.expect(headerValue).to.equal('expected-value'); });
Quick Reference
| Action | Code Snippet | Description |
|---|---|---|
| Get header value | pm.response.headers.get('Header-Name') | Retrieve the value of a response header |
| Assert header equals | pm.expect(value).to.equal('expected') | Check if header value matches exactly |
| Assert header contains | pm.expect(value).to.include('text') | Check if header value contains a substring |
| Check header exists | pm.expect(value).to.not.be.undefined | Verify header is present in response |
Key Takeaways
Use pm.response.headers.get('Header-Name') to access response headers in Postman tests.
Always assert header values with pm.expect() for clear pass/fail results.
Check if a header exists before asserting its value to avoid errors.
Header names are case-insensitive but must be spelled correctly in get().
Use .to.equal() for exact matches and .to.include() for partial matches.