Provide variable from Request to Collection's prerequest script

Hi there, is there any possibility to provide parameter from request to collection’s prerequest script?

In collection’s prerequest script I have an function to login user and get Bearer token, but user’s guard can be customer / user / admin. For some requests I need to be logged as Customer for others as User or Admin.

I tried following:
Request’s prerequest script:

let guardType = 'admin';
pm.environment.set("guardType", guardType);

Collection’s prerequest script

guardType = pm.environment.get('guardType');

But of course, Collection’s prerequest script runs before Request’s script, so guardType is not provided to it. Is there any solution how to define some variable per Request and use it in Collection’s prerequest script?

Hi @PetrKaterinak

I think the best approach would be to store the guard type and request name in a JSON file and add using the Collection Runner or use a collectionVariable and then you can use the Collection Pre Request to set the token.

For Example:

JSON File

[
{
“guardType”: “admin”,
“requestName”: “Request1”
},
{
“guardType”: “user”,
“requestName”: “Request1”
},
{
“guardType”: “customer”,
“requestName”: “Request1”
}
]

Now, in your Collection PreRequest, you can call from the iterationData, and each iteration will create the token it needs and then can the request it needs to run against

Collection PreRequest:
guardType = pm.iterationData.get(“guardType”);

Collection Tests:
postman.setNextRequest(pm.iterationData.get(“requestName”);

NOTE: just make sure that Request1, 2 and 3 all have a line in the Tests of:
postman.setNextRequest(null);
This is needed so that it does not attempt to run all the Requests, just the one that you need.

I hope this helps.