Add capabilities to a backend service

This article shows an Azure API management policy sample that demonstrates how to add capabilities to a backend service. For example, accept a name of the place instead of latitude and longitude in a weather forecast API. To set or edit a policy code, follow the steps described in Set or edit a policy. To see other examples, see policy samples.


Paste the code into the inbound block.

<!-- The policy defined in this file shows how to use a few policies to add a capability to a backend service. -->

<!-- API was used as a backend service in this example. The snippet contains enough information for reconstituting the setup and testing the policy. -->
<!-- The snippet shows how to accept a name of the place instead of latitude and longitude in a weather forecast API. -->

<!-- Copy the following snippet into the inbound section and look at the trace window to see it work. -->

    <base />
    <!-- Check if lat/long has already been cached for this place and fetch it into a variable. -->
    <cache-lookup-value key="@(context.Request.MatchedParameters.GetValueOrDefault("place="""))" variable-name="latlong"/>

    <!-- If no lat/long found, use external API to get lat/long of the place and cache it. -->
      <when condition="@(!context.Variables.ContainsKey("latlong="""))">

        <!-- Lookup lat/long for the place. -->
        <send-request mode="new" response-variable-name="response" timeout="10" ignore-error="false">
            var code = context.Request.MatchedParameters.GetValueOrDefault("place");
            var key = "{{google-geo-api-key}}";
            return $"{code}&key={key}";

        <!-- Extract a JSON object containing lat/long from the response and serialize it into a variable. -->
        <set-variable name="latlong" value="@(((IResponse)context.Variables["response="""]).Body.As<JObject>

          <!-- Cache lat/long for a an hour (coould be for much longer of course, since places don't move very often). -->
          <cache-store-value key="@(context.Request.MatchedParameters.GetValueOrDefault("latlong="""))" value="@((string)context.Variables["latlong="""])" duration="3600"/>

    <!-- Change forwarding URL to the form expected by the backend, i.e. containing the key and lat/lng.  -->
    <rewrite-uri template="@{
            var loc = JObject.Parse((string)context.Variables["latlong=""

    <base />
    <base />
    <base />

Next steps

Learn more about APIM policies: