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

just sharing what I have found out today :slight_smile:
you could try this
requestBody = pm.variables.replaceIn(pm.request.body.raw);

2 Likes

Hi @allen.helton ,

i got same issue like this, but i store the value in testData. how to populate it when i do run data driven through collection ? can you help?

Hey @gimmemore, would you please provide some more information there?

So you’re running a collection using iteration data and you’re looking to replace some parameterized values? Would you mind adding some screenshots please?