Is there a way to automatically encode urls?

I am working with some endpoints that take Chinese characters as part of the url parameter. Is there a way to automatically encode urls?

/api/v1/word/你好

Normally I would just have the client encodeURI before sending the request. I’m finding it rather frustrating to have to manually convert all of my urls before using them with postman. It also turns things into something like %E4%BD%A0%E5%A5%BD which means I have to decode it again if I happen to forget what it was beforehand.

Is there a way where the Chinese part of the URL can be put inside a variable? If so, then you can use the pre-request script to read the variable and encode it. Albeit it becomes a bit unreadable compared to having the complete URL.

Also curious, these should get auto encoded, isn’t it @SamvelRaja?

I had the same problem encoding search queries from a data file doing requests in the request runner.

*** Data file ***
q”,
“你好”,

*** Pre request ***
let encoded = encodeURIComponent(data.q);
pm.environment.set(‘query’, encoded);

*** reqeuest URL ***
/api/v1/word/{{query}}

Hope this helps!

pm.request.url.query = encodeURIComponent(pm.request.url.query);

This worked for me for URLs with query parameters which need encoding. As the query is a well-defined component of the URL, we can just encode that part using a pre-request script. No need to have variables there. This is not your exact case, but it might be useful for folks using URLS with query strings that need to be encoded.

1 Like

That’s what actually works for me all the time with query parameters (not URL), but maybe adapted:

//console.log("----- Encode query string");
//console.log("Input: " + pm.request.url.query.toString());
var querycount = pm.request.url.query.count();
for(let i = 0; i < querycount; i++) {
  //console.log(i + "/" + pm.request.url.query.idx(i).key + ": " + encodeURIComponent(pm.request.url.query.idx(i).value));
  pm.request.url.query.idx(i).value = encodeURIComponent(pm.request.url.query.idx(i).value);
}
//console.log("Output: " + pm.request.url.query.toString());
2 Likes

Thanks for sharing this!