0
0
Postmantesting~5 mins

Response body assertions in Postman

Choose your learning style9 modes available
Introduction

Response body assertions check if the data returned from an API is correct. This helps make sure the API works as expected.

When you want to verify that an API returns the right user details after login.
When checking if a product list API returns the expected number of items.
When validating that an error message appears in the response after a bad request.
When confirming that a new record was created and returned correctly by the API.
Syntax
Postman
pm.test("Test description", function () {
    let jsonData = pm.response.json();
    pm.expect(jsonData.key).to.eql(expectedValue);
});

Use pm.response.json() to parse the response body as JSON.

Use pm.expect() with to.eql() to compare values exactly.

Examples
This test checks if the response has a name field equal to "Alice".
Postman
pm.test("Check user name", function () {
    let jsonData = pm.response.json();
    pm.expect(jsonData.name).to.eql("Alice");
});
This test confirms the response has exactly 5 products in the list.
Postman
pm.test("Verify product count", function () {
    let jsonData = pm.response.json();
    pm.expect(jsonData.products.length).to.eql(5);
});
This test checks if the error message contains the text "Invalid request".
Postman
pm.test("Error message present", function () {
    let jsonData = pm.response.json();
    pm.expect(jsonData.error).to.include("Invalid request");
});
Sample Program

This test verifies that the response body contains a userId of 12345 and a status of "active".

Postman
pm.test("Response body has correct user ID and status", function () {
    let jsonData = pm.response.json();
    pm.expect(jsonData.userId).to.eql(12345);
    pm.expect(jsonData.status).to.eql("active");
});
OutputSuccess
Important Notes

Always parse the response body before making assertions.

Use clear test names to describe what you are checking.

Check for both exact matches and partial matches depending on your needs.

Summary

Response body assertions check the data returned by an API.

Use pm.response.json() to read the response body.

Write clear tests to confirm the API returns expected values.