0
0
Postmantesting~5 mins

Header assertions in Postman

Choose your learning style9 modes available
Introduction

Header assertions check if the response headers from a server are correct. This helps ensure the server sends the right information about the response.

When you want to confirm the content type of the response is JSON.
When you need to verify the server sends a specific security header.
When checking if the response includes caching instructions.
When validating the response language or encoding.
When ensuring the server returns expected custom headers.
Syntax
Postman
pm.test("Header assertion name", function () {
    pm.response.to.have.header("Header-Name");
    pm.expect(pm.response.headers.get("Header-Name")).to.eql("Expected-Value");
});

Use pm.response.to.have.header() to check if a header exists.

Use pm.response.headers.get() to get the header value for exact matching.

Examples
This test checks if the response has a Content-Type header and if it includes 'application/json'.
Postman
pm.test("Content-Type is JSON", function () {
    pm.response.to.have.header("Content-Type");
    pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json");
});
This test verifies the Server header exactly equals 'nginx'.
Postman
pm.test("Server header is correct", function () {
    pm.response.to.have.header("Server");
    pm.expect(pm.response.headers.get("Server")).to.eql("nginx");
});
This test only checks if the Cache-Control header is present, without checking its value.
Postman
pm.test("Cache-Control header exists", function () {
    pm.response.to.have.header("Cache-Control");
});
Sample Program

This Postman test script checks two headers: it confirms the Content-Type header exists and includes 'application/json', and it verifies the Server header exactly equals 'nginx'.

Postman
pm.test("Check Content-Type header", function () {
    pm.response.to.have.header("Content-Type");
    pm.expect(pm.response.headers.get("Content-Type")).to.include("application/json");
});

pm.test("Check Server header", function () {
    pm.response.to.have.header("Server");
    pm.expect(pm.response.headers.get("Server")).to.eql("nginx");
});
OutputSuccess
Important Notes

Header names are case-insensitive but use the exact casing for readability.

Use to.include() when the header value may have extra details (like charset).

Check for header existence before checking its value to avoid errors.

Summary

Header assertions verify the presence and value of response headers.

They help confirm the server sends correct metadata about the response.

Use Postman's pm.response.to.have.header() and pm.expect() for clear tests.