We often come across where we need to generate our backend URL dynamically and use it to call the downstream systems.
In IBM APIC we use gatewayscript policy to write custom code and can generate a dynamic URL based on the requirement. We can call the backend directly from gatewayscript using urlopen after generating it dynamically but here we are looking to use the dynamic URL generated in next invoke policy.
To achieve above we are going to use here context variable, we will save the dynamically generated backend URL in a context variable (In below example we have used a hardcoded URL value for test and set it to a variable named foo)

Then we reference that context variable set in gatewayscript on the URL option of Invoke policy.

On calling API, it gets the backend target endpoint from the URL set on Invoke policy which gets its value from the context variable set in gatewayscript.
