Accessing request.data with filled body parameters in pre-request script

I have the following request body:

{
    "data": [
        {
            "productId": "{{productId}}",
            "quantity": 2,
            "attributes": {
                "startAt": "2019-12-13T17:58:44.000Z",
                "endAt": "2019-12-30T17:59:44.000Z"
            }
        }
    ]
}

In a pre-request script, I want to access this content… but with the ‘productId’ populated. Right now, when I attempt to access it (using request.data or pm.request.body) I get back the raw content with that actual “{{productId}}” template tag and not the value that should be inserted into it.

If you’re in the pre-request script then you’re going to have to use the js client to resolve your variables.

let productId = pm.environment.get("productId");

Allen,

I can get the variable from the environment, no issues. What I need is the entire request body with the {{productId}} swapped out with that value. Whether I can do it with a simple command, or use some kind of replace function to replace {{productId}} with what’s returned with pm.environment.get(“productId”). What I’m trying to do is create a hash that is used for authorization from the request payload. Since the actual payload going to the end-user uses the actual product ID and not “{{productId}}”, the hash that I create is wrong. Hope that makes sense. If not, let me know so I can clarify further.

So maybe some simple javascript to do what you want?

let productId = pm.environment.get("productId");
let requestBody = JSON.parse(<enter your request body here>);
for(let i = 0; i < requestBody.data.length; i++){
  requestBody.data[i].productId = productId;
}

That worked… appreciate it!

1 Like