Home > Mobile >  Can I compose variable to create new varibales in Postman?
Can I compose variable to create new varibales in Postman?

Time:07-06

I have a variable as BASE_URL. When I am using the localhost, I am composing it with one more variable PORT that reflects the port on which the service is running on my local. These two variables composed as {{BASE_URL}}:{{PORT}} defines the complete base URL for my APIs.

But when testing the deployed version of my API, my base URL is just https://www.xyzapi.com without any port declared explicitly.

I am using {{BASE_URL}}/rule-service/v1/find-by-txn format in the request URL. I am using environments to switch between local and remote.

How can I utilize the same request format for both cases? I have multiple microservices running on different ports.

CodePudding user response:

This code did the job!

let baseUrl = pm.environment.get("BASE_URL");

if(baseUrl === 'localhost'){
    let port = pm.collectionVariables.get("PORT");
    baseUrl = `${baseUrl}:${port}`;
}

pm.environment.set("BASE_URL", baseUrl);

CodePudding user response:

Try this. It introduces a variabe FINAL_BASE_URL which is to be used to build your URLs (eg {{FINAL_BASE_URL}}/rule-service/v1/find-by-txn) and it includes the PORT or not, depending if an environment variable PORT is set.

if (pm.environment.get("PORT")) { 
    let FINAL_BASE_URL = pm.environment.get("BASE_URL")   ":"   pm.environment.get("PORT")
} else {
    let FINAL_BASE_URL = pm.environment.get("BASE_URL")
}
  • Related