postman

Update request URL in pre-request script


Is it possible to update url of postman request in the pre-request script. I want to edit the URL based on dynamic environment input.

For example:

if (environment.someValue) {
    request.url = request.url + "\" + environment.someValue
    if (environment.anotherValue) {
        request.url = request.url + "\" + environment.anotherValue
    }
}
    
console.log(request.url);

The above code gives me prefect console log:

e.g. if url is https://someServer/someRequest, environment.someVar is x and environment.anotherVar is y the console.log(request.url) above prints:

https://someServer/someRequest/x/y

But the problem is (say if i am requesting a Get), even after logging the overridden request url, it only calls https://someServer/someRequest and does not override to https://someServer/someRequest/x/y.

Any ideas how to modify the url as asked above.


Solution

  • If the URL in your request is set as global, it should work. E.g. I have a GET request:

    GET http://{{myurl}}/etc. with myurl set to a global variable.

    In my pre-request script I do pm.globals.set("myurl", <new url>);

    When I launch the request, it tries to do a GET request on my new URL.

    So it is possible to do but you have to use global or environment variables to dynamically update your request:

    set your 'someRequest' as a global that you can update in your prescript (instead of request.url), then it will be interpreted when you launch your request:

    https://someServer/{{someRequest}}