Azure APIM policy samples - Part 1

Azure APIM policy samples - Part 1

Below are some samples of commonly used API management policies that can be useful.

Get access token from APIM Authorizations and add it to the request header

  1. Create authorizations in APIM. Note provider name and authorization name are configured here. These names are used in policy to get token. To know more about how to configure Authorizations, click here.

  2. Configure policy to read token from authorization created above.

 <inbound>
<!-- get bearer token from authorizations and set in header  -->
        <get-authorization-context provider-id="app1-stg-auth-ad" authorization-id="app1-stg-auth" context-variable-name="auth-context" identity-type="managed" ignore-error="false" />
        <set-header name="Authorization" exists-action="override">
            <value>@("Bearer " + ((Authorization)context.Variables.GetValueOrDefault("auth-context"))?.AccessToken)</value>
        </set-header>
 </inbound>

Store request body payload in variable and send it to another API using send-request policy

  1. Create a variable to store the request payload.

     <set-variable name="var1body" value="@{
         string inBody = context.Request.Body.As<string>(preserveContent: true);    
         return inBody;
     }" />
    
  2. Configure send request policy - set url, method, header parameters, and request body as below

     <send-request mode="new" response-variable-name="second-request" timeout="20" ignore-error="true">
                 <set-url>https://sample.url.com/upload</set-url>
                 <set-method>PUT</set-method>
                 <set-header name="Authorization" exists-action="override">
                     <value>@("Bearer " + ((Authorization)context.Variables.GetValueOrDefault("auth-context"))?.AccessToken)</value>
                 </set-header>
                 <set-header name="header1" exists-action="override">
                     <value>value1</value>
                 </set-header>
                 <set-header name="header2" exists-action="override">
                     <value>value2</value>
                 </set-header>
     <!-- use variable created above as request body -->
                 <set-body>@(context.Variables.GetValueOrDefault("var1body",""))</set-body>
             </send-request>
    

choose-when, return-response

Check the response of the above send-request and create a custom API response based on the condition using choose-when policy

<choose>
   <!-- Check StatusCode property in response -->
   <when condition="@(((IResponse)context.Variables["second-request"]).StatusCode != 200)">
     <!-- Return 401 Unauthorized with http-problem payload -->
                <return-response>
                    <set-status code="401" reason="failed" />
                    <set-body>unexpected error</set-body>
                </return-response>
            </when>
        </choose>

Read Named values in policy

Named values feature in APIM allows user to create common configuration key-values or secrets and it can be referenced in policy using syntax- {{<key_name>}}.

Example-

I have created a Named value with key operation-config and used its value in rewrite url as below.

<rewrite-uri template="@{ return "{{operation-config}}"+"/"+context.Request.MatchedParameters["filePath"];}" copy-unmatched-params="false" />

Read API template parameters in policy

If we have created any template parameter in API operation, then we can access it in policy.

Example-

Created a template parameter as filePath.

We can access it as- context.Request.MatchedParameters["filePath"]

<rewrite-uri template="@{ return "{{operation-config}}"+"/"+context.Request.MatchedParameters["filePath"];}" copy-unmatched-params="false" />

Read request headers

In the below example, we are reading header parameter names Tags and using that value to add explicit header with name as blob-tags.

<set-header name="blob-tags" exists-action="override">
    <value>@(context.Request.Headers.GetValueOrDefault("Tags",""))</value>
</set-header>

Call custom liquid template

  1. Below sample shows liquid template loops through API response JSON array value which is present in response body. From each array item, it reads displayName, id and creates output array.
<outbound>
    <base />
    <set-body template="liquid">
  {"result":
    [
    {%JSONArrayFor item in body.value %}{ "displayName" : "{{     item.displayName }}",
    "id" : "{{ item.id }}"
    } {% endJSONArrayFor %}
    ]
}
    </set-body>
</outbound>

Example-

JSON array on which liquid template is applied-

{
    "value": [{
        "@odata.type": "",
        "id": "123456",
        "deletedDateTime": null,
        "description": "",
        "displayName": "Admin",
        "roleTemplateId": "xxxx"
    }, {
        "@odata.type": "",
        "id": "654321",
        "deletedDateTime": null,
        "description": "",
        "displayName": "Bob",
        "roleTemplateId": "xxxx"
    }, {
        "@odata.type": "",
        "id": "111111",
        "deletedDateTime": null,
        "description": "",
        "displayName": "Alex",
        "roleTemplateId": "xxx"
    }]
}

Liquid template transformed output

{
    "result": [
        {
            "displayName": "Admin",
            "id": "123456"
        },
        {
            "displayName": "Bob",
            "id": "654321"
        },
        {
            "displayName": "Alex",
            "id": "111111"
        }
    ]
}

Thanks for reading.

Did you find this article valuable?

Support Suraj Somani by becoming a sponsor. Any amount is appreciated!