0
0
Postmantesting~5 mins

Body validation before sending in Postman

Choose your learning style9 modes available
Introduction

We check the request body before sending it to make sure it has the right data. This helps avoid errors and saves time.

When sending data to create a new user, check the body has all required fields.
Before updating a product, verify the body contains valid price and name.
When testing an API, ensure the body format matches what the server expects.
Before sending sensitive data, confirm the body does not have empty or wrong values.
Syntax
Postman
pm.test("Body has required fields", function () {
    let jsonData = pm.request.body && pm.request.body.raw ? JSON.parse(pm.request.body.raw) : {};
    pm.expect(jsonData).to.have.property('name');
    pm.expect(jsonData).to.have.property('email');
});

Use pm.request.body.raw to access the raw JSON body before sending.

Use pm.expect assertions to check if required fields exist.

Examples
This test checks if the body has both 'username' and 'password' fields before sending.
Postman
pm.test("Body contains 'username' and 'password'", function () {
    let body = JSON.parse(pm.request.body.raw);
    pm.expect(body).to.have.property('username');
    pm.expect(body).to.have.property('password');
});
This test ensures the 'age' field in the body is a number.
Postman
pm.test("Body 'age' is a number", function () {
    let body = JSON.parse(pm.request.body.raw);
    pm.expect(body.age).to.be.a('number');
});
This test confirms the body is not empty before sending.
Postman
pm.test("Body is not empty", function () {
    pm.expect(pm.request.body.raw).to.not.be.empty;
});
Sample Program

This Postman test script checks that the request body is not empty and contains 'title' and 'description' fields as strings before sending the request.

Postman
pm.test("Validate request body before sending", function () {
    let bodyText = pm.request.body.raw;
    pm.expect(bodyText).to.not.be.empty;
    let body = JSON.parse(bodyText);
    pm.expect(body).to.have.property('title');
    pm.expect(body).to.have.property('description');
    pm.expect(body.title).to.be.a('string');
    pm.expect(body.description).to.be.a('string');
});
OutputSuccess
Important Notes

Always parse the raw body safely to avoid errors if the body is empty or not JSON.

Use clear and simple assertions to catch missing or wrong data early.

Running these tests before sending helps prevent server errors and saves debugging time.

Summary

Check the request body before sending to avoid errors.

Use Postman tests with pm.request.body.raw and pm.expect to validate data.

Validate required fields and data types to ensure correct requests.