What is the simplest way to URL encode the output from pm.request.url.getPathWithQuery?


In my pre-request script, I need to use the exact same request URL string that Postman uses in its request. For example, if I specify a parameter as that include quote and spaces, such as:

keyName          "Some Value"

When Postman sends the request, it semi-URL-encodes the request such that the URL now looks something like this:

OPTIONS https://domain/api/v3/endpoint?keyName=%22Some%20Value%22

So, only the parameter VALUES are URL encoded.

However, when I use the pm.request.url.getPathWithQuery in my pre-requests script, it returns the actual text used in the parameter, i.e. with quote and spaces:

const BaseURL = pm.collectionVariables.get("BaseURL");
const Endpoint = pm.request.url.getPathWithQuery();

console.log(BaseURL + Endpoint);
https://domain/api/v3/endpoint?keyName="Some Value"

If I then wrap the pm.request.url.getPathWithQuery with encodeURIComponent, it encodes too much of the URL:

const BaseURL = pm.collectionVariables.get("BaseURL");
const Endpoint = encodeURIComponent(pm.request.url.getPathWithQuery());

console.log(BaseURL + Endpoint);

How can I get ONLY what Postman uses?

For info, the URL used in the request is also used to construct an HMAC Signature, so I need to get this exactly to build the authorisation header. The default authorisations options do not work in this case.

I should say that there are many parameters across multiple requests, so hardcoding them probably won’t be that useful.

I’m sure I am missing something obvious, but I cannot figure out what that is for the life of me.

Ok, thanks to the very last line on this post (Encoding automatically in Postman - Stack Overflow), I think I have found the cure:

const EncodedURL = encodeURI(pm.variables.replaceIn(pm.request.url));