Postman request body in Pre-request script
Asked Answered
T

2

14

I have a Postman Pre-request script to add a HMAC key to a request. This works great unless the body has an environment variable in it. So if I have the following body

{
    "key": "{{key}}",
    "value": "some value"
}

When with the key value set to be sample when the request is sent, the body contains the following

{
    "key": "sample",
    "value": "some value"
}

This is what I would expect to happen. However when accessing the request body in the Pre-Request Script,

console.log(pm.request.body.toString());

I get the following

{
    "key": "{{key}}",
    "value": "some value"
}

How can I get the body with the variables having been replaced, so that it is what would be sent to the server?

Ternate answered 15/11, 2019 at 12:24 Comment(0)
R
20

You can interpolate the placeholders using following function:

function interpolate (value) {
    const {Property} = require('postman-collection');
    return Property.replaceSubstitutions(value, pm.variables.toObject());
}

In your case:

console.log(interpolate(pm.request.body.toString()));
Reedy answered 15/11, 2019 at 12:38 Comment(1)
Simple and easy and works perfectly with Postman v7.12.0. Thank youAthallia
T
2

Just in case anyone finds this you can use this instead now.

var requestBody = pm.variables.replaceIn(pm.request.body);
Tripper answered 29/1 at 2:32 Comment(1)
Simplest answer that works well in my caseCould

© 2022 - 2024 — McMap. All rights reserved.