How to Verify Body values in a Post Request

Hi, I am new to POSTMAN and trying to validate the data to be not null, empty or undefined in a pre-request script of Request Body.

This is the data I am passing in a request body.

{
    "name": "{{$randomFirstName}}",
    "number": "0123456789",
    "catid": 14,
    "catname": "abc",
    "createdby": "admin"
}

Following is my pre-request script to verify the values to be not null, but this isn’t working and the test case is also passing if I pass a null value in the request body.

const reqBody = request.data;

pm.test("Verify the values are not null", function () {
    pm.expect(reqBody.name).to.not.null;
    pm.expect(reqBody.number).to.not.null;
    pm.expect(reqBody.catid).to.not.null;
    pm.expect(reqBody.catname).to.not.null;
    pm.expect(reqBody.createdby).to.not.null;
});

Hey @salmankhan94

Not sure where you’re getting request.data from?

Have you tried:

const reqBody =JSON.parse(pm.request.body.raw)

If you’re ever having issues with something in the sandbox, a good tip is to just console.log() to see what data is being assigned to certain variables.

1 Like

HI @salmankhan94

In your Test Script did you try as below?

var req = JSON.parse(request.data);
pm.test("Verify the name"  , function () {
    pm.expect(req.name, 'Name is not null').to.not.be.null;
});

Is this what you are expecting?

3 Likes

Yes, it worked. Seems like JSON.parse(request.data) is the difference. Thanks

1 Like

Using JSON.parse(pm.request.body.raw) is the same thing as JSON.parse(request.data) but it’s using the newer pm.* API syntax, that’s the reason why I suggested that. :smiley:

There was nothing wrong with your test, it was just the reference that you were making to the request body data.

const reqBody = JSON.parse(pm.request.body.raw)

pm.test("Verify the values are not null", function () {
    pm.expect(reqBody.name).to.not.null;
    pm.expect(reqBody.number).to.not.null;
    pm.expect(reqBody.catid).to.not.null;
    pm.expect(reqBody.catname).to.not.null;
    pm.expect(reqBody.createdby).to.not.null;
});
5 Likes

Yes Danny you are right. Thanks for the help man. Appreciate the prompt response from you guys.

2 Likes

Glad now its clear :slight_smile:

4 Likes