I have a problem where I have an optional HTTP Header that specifies which sandbox my API call should hit. leaving this field blank resolves to the production “sandbox”.
Ideally i’d like to create a Postman Env that doesn’t have this field at all, but create collections that include it. It seems that if I set my HTTP Header to have: x-sandbox : {{SANDBOX_NAME}} and SANDBOX_NAME env variable is not set, it will send the actual string value of {{SANDBOX_NAME}} in the http header, which of course confuses/breaks the API.
Is there some way I can denote my x-sandbox HTTP header to only send if the associated variable is defined?
My collection is re-used across a large team, so I’d like to make this declaration IN the postman collection itself (rather than in a Postman app config, or in the Postman env file since those are not shared across the users of this collection)
Yes this is possible! Doing some quick testing, I was able to produce the following for you:
if (pm.environment.get("SANDBOX-NAME") === "") {
pm.request.headers.remove("x-sandbox")
}
If you place the above in a Pre-Request script, you will see your desired behavior.
Here I check if that variable has no value assigned to it. If it does not, it removes the “x-sandbox” header, just as desired. Then otherwise, It will leave the header in there and it gets passed along with the resolved value.
For further reference, check out this video I made on Pre-Request and Test Scripts.
Thanks - i was hoping for a simple JSON key/value - ill see if i can figure out how to get this into my Swagger -> Postman Collection conversion script in a sane way. Appreciate the feedback!