Use Existing Postman Request in Pre/Post Script

Hi,

I scoured the docs and the internet to see if this is possible but was unable to find anything. Is there a way to use an existing Postman request that’s defined within the same collection or different collection in a pre/post script? I know there’s a pm.sendRequest function, but it just strikes me as inefficient to have to define the request again.

Thanks,
Quy

Hi @cryosat-candidate-16! Welcome to the community forum! :trophy:

I think what you be looking for is the setNextRequest method. You can use this to programmatically set the next request based on your own conditional logic in the Pre-request or Tests tab. Here’s a bit more information on controlling your workflow within Postman.

Hope that helps!

1 Like

Thanks @sean.keegan for the reference and the prompt response.

I looked at the docs and it looks like it sets the workflow and you can’t make use of the response in a pre-script. My use case here is that I have to auth against a login endpoint and then use the generated token as in an auth header for another request. I have to do this for all requests for a particular REST resource. I would like to just automate by defining a collection pre script that is executed before each call, calls the auth endpoint, grabs the token and sets the token as a collection ENV var. My other requests would then use that ENV var to set its auth headers.

It’s not a big deal if it’s not possible as I can just accomplish this through the sendRequest function.

1 Like

Ah okay! I think what you may want to do is take advantage of the pre-request script at the collection level then. Anything in the pre-request script of the collection level folder will run before each and every request in the collection.

If I’m understanding your need and use case correctly, one of our Postman community superstars @praveendvd has demonstrated something similar to this in his public workspace. Check it out here and see if this is something that might be useful for what you’re looking for - specifically look at the pre-request tab of the collection level folder.

3 Likes

@sean.keegan :face_with_hand_over_mouth: thanks sean for the kind words :sparkling_heart: happy to see the public workspace being mentioned .

@cryosat-candidate-16 just store the request you want as a variable

In the test script of the req you want to send in prerequest add:

   pm.environment.set("req", pm.request)

And in pre-request script where u want to send it use;

  pm.sendRequest(pm.environment.get("req"))
3 Likes

Thanks to the both of you. Saving the request object in an env worked.

3 Likes