Home > other >  How to retrieve global varibles configured on the request url in the pre-request script
How to retrieve global varibles configured on the request url in the pre-request script

Time:04-22

I am preparing a postman sample that uses some global variables in the url parameters.

enter image description here

The valibles {{api-url}} and {{public-address}} are defined under Globals.

enter image description here

I also have a script in Pre-request Script where it tries to retrieve the request url.

var url = pm.request.url
console.log("URL="   url)

However when I run this I do not get the url with the global variables filled in. Instead I get the below;

enter image description here

For the request itself I get the varibales filled in , I had to mask them due to privacy reasons.

I believe at the time of the Pre-reuest script the request url may not have filled with global variables? If so how can I get these valies in the url?

I definitely can re construct the URL in the Pre-request script itsef, but then that would duplicate things ...

CodePudding user response:

It appears that the actual request is resolving those values in the UI. If you're just needing to resolve the same in the log output, it would be like this:

let url = pm.request.url
console.log("URL="   pm.variables.replaceIn(url))

As the log statement is just a string value of the UI, the variables are displayed as they are in the request URL. You would need to use replaceIn() to substitute those for the resolved values.

https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/#the-pm-object

  • Related