Rewrite a target URL dynamically on Apigee Edge.
This sample uses these policies:
Extract Variables: To extract part of the request path into a variable.
JavaScript: Rewrites the target URL.
This sample API proxy illustrates how to change the target endpoint URL using a JavaScript policy to set the target.url flow variable. This variable holds the complete URL for the back-end target endpoint, including any query parameters.
-
Deploy the proxy.
-
Send this request to Apigee Edge.
Note: The proxy is configured with a base path of
/zip. The incoming request must contain that base path or the request will not be processed. Tip: Take a look at theapiproxy/proxies/default.xmlto see where this base path is configured.curl http://myorg-test.apigee.net/zip/80301 -
An Extract Variables policy extracts the part of the path that comes after the
/zipbase path. -
The policy stores the value of the zip code in a flow variable called
LOCATION.zip. This value is specific to the back-end API. It identifies the locale for which to return geographical data. Here is the policy XML:<ExtractVariables name="extractZip"> <DisplayName>getZipfromPath</DisplayName> <URIPath> <Pattern ignoreCase="true">/{zip}</Pattern> </URIPath> <IgnoreUnresolvedVariables>false</IgnoreUnresolvedVariables> <VariablePrefix>LOCATION</VariablePrefix> </ExtractVariables>
-
A JavaScript policy rewrites the target URL by setting the
target.urlflow variable. This expression also appends theLOCATION.zipvalue to the query parameteraddress.context.setVariable("target.url", "http://maps.googleapis.com/maps/api/geocode/json?address="+context.getVariable("LOCATION.zip")); -
Finally, the newly formed target request is sent to the backend target, the Google maps API, and the geographical information for the specified zip code is returned.
See the main project README file for information about setting up, deploying, and invoking sample proxies.
This screen shot from the Apigee Edge trace tool shows the placement of the policies used in this sample.
Policies used in this sample
Related information
Copyright © 2017 Apigee Corporation
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

