You are currently viewing Azure: Policies in API Management

Azure: Policies in API Management

In my previous article, I have explained how to create API management instance and how to expose API through API management using Azure portal.

This article explains what are policies and how they should be used.

You will need to Azure Portal access to understand the topic. If you do not have access, then you can create free account on Azure.

What are policies ?

Fundamentally, policies are powerful capabilities provided by API management which allow changing behavior of API through configurations.

Policies are collection of statements which are executed sequentially on request or response of an API.

These statements may include limiting call rate, setting header, changing JSON to XML, etc.

Please note that policies are executed in the API Management instance

Let’s go deeper !

Below diagram shows the high level overview of policies in API management.

Policy Overview

Policy Definition

Policies are written in an XML document. Below code snippet shows the XML schema which is used for writing the policies.

Few important things to note:

  • Inbound Policies – These policies are executed when the API management API is called.
  • Backend Policies – These policies are executed when API management calls the Backend APIs
  • Outbound Policies – These policies are executed when API management returns the response to the caller.
  • On-Error Policies – If there are any errors during execution, all the policies would be skipped, and on error policies would be executed. (think of this like a catch block in try-catch statement in C#)

Every statement is XML element with razor view like syntax.

<policies>

  <inbound>

    <!-- to be applied to the request go here -->

  </inbound>

  <backend>

    <!-- to be applied before the request is forwarded to 
         the backend service go here -->

  </backend>

  <outbound>

    <!-- to be applied to the response go here -->

  </outbound>

  <on-error>

    <!-- to be applied if there is an error condition go here -->

  </on-error>

</policies> 

Policy Statements

There are different type of policy statments. There are statements to set a variable in the API management context, there are choose-when statements, etc.

Below are the examples:


<choose>

    <when condition="Boolean expression | Boolean constant">
        <!— one or more policy statements to be applied if the above condition is true  -->
    </when>

    <when condition="Boolean expression | Boolean constant">

        <!— one or more policy statements to be applied if the above condition is true  -->

    </when>

    <otherwise>

        <!— one or more policy statements to be applied if none of the above conditions are true  -->
    </otherwise>

</choose>

<set-variable name="isMobile" value="@(context.Request.Headers["User-Agent"].Contains("iPad") || context.Request.Headers["User-Agent"].Contains("iPhone"))" />


Policy Expressions

Policy expressions are C# code blocks. They look to be exactly similar to Razor syntax. Only thing to remember is that every policy expression MUST have a return statement.

Below are the examples of policy expressions. If you want to read more about them, please refer the MSDN documentation.


@(true)

@((1+1).ToString())

@("Hi There".Length)

@(Regex.Match(context.Response.Headers.GetValueOrDefault("Cache-Control",""), @"max-age=(?\d+)").Groups["maxAge"]?.Value)

@(context.Variables.ContainsKey("maxAge") ? int.Parse((string)context.Variables["maxAge"]) : 3600)

@{
  string value;
  if (context.Request.Headers.TryGetValue("Authorization", out value))
  {
    return Encoding.UTF8.GetString(Convert.FromBase64String(value));
  }
  else
  {
    return null;
  }
}

Scope

Policy can be assigned globally to API management instance – meaning it would be applicable to all products / APIs / operations inside that API management instance.

Policies can also be applied to either Product level or API level or Operation level.

The XML schema for defining policies is same for all the levels. Then the obvious question is how to specify scope.

Please refer this MSDN article which specifies how policies can be assigned to different levels.

Execution Order

Policies are executed sequentially and their order is decided by the order.

If you have a policy at the global level and a policy configured for an API, then whenever that particular API is used both policies will be applied.

API Management allows for deterministic ordering of combined policy statements via the base element.

In below example, cross domain policy would be executed first, then higher level policies would be executed and then the find and replace policy is executed.

<policies>     
    <inbound>         
         <cross-domain />         
         <base />       
         <find-and-replace from="xyz" to="abc" />     
    </inbound> 
</policies>

Policy Samples Reference

You can find many interesting policy samples in this documentation page. The samples include how to Authorize using Google’s OAuth, or How to log errors to Stackify, OR authorization based on JWT claims, etc.

I hope this article helped you to understand the API Management policies. If this article helped you, please do comment and let me know your thoughts.

Leave a Reply