Search code examples
azureazure-management-api

Set Response Header With remaining-calls Azure API Management


I'm using Azure API Management with some rate limiting based on subscription. I need to send to the user in the response headers the number of remaining calls. I know that I should set some values in the outbound policy but I do not know how to do it exactly. This is my policy XML if any one can help.

<policies>
    <inbound>
        <base />
        <set-variable name="remainingCalls" value="remaining-calls-variable-name" />
        <quota-by-key calls="5" renewal-period="86400" counter-key="@(context.Subscription?.Key ?? "anonymous")" increment-condition="@(context.Response.StatusCode >= 200 && context.Response.StatusCode < 300)" />
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
        <set-header name="remainingCalls" exists-action="append">
        <value>@(context.Response.Headers.GetValueOrDefault("remaining-calls-header-name","2"))</value>
    </set-header>
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

Solution

  • I've contacted Microsoft Azure support for this request and they were able to guid me to a possible workaround that may be helpful. In my particular use case it is good solution. For quota policy and as mentioned by @Venkatesh-MAT it is not supported to retrieve remaining quota information in response header as rate-limit policy. However there is a separate REST API for this purpose. This is documentation for the same https://learn.microsoft.com/en-us/rest/api/apimanagement/current-ga/quota-by-counter-keys/list-by-service.

    The API in this documentation requires bearer token as authentication. To be able to generate the bearer token you can simply use azure cli to get token for the resource using command az account get-access-token --resource https://management.azure.com or if you need to do it programmatically you have to follow below steps:

    1. Set principle role using azure cli with subscription scope to create service principle that have access on this resource scope (az ad sp create-for-rbac -n "principle-1" --role contributor –scopes /subscriptions/{subscriptionID}/resourceGroups/{resourcegroup}/providers/Microsoft.ApiManagement/service/{API management Service name} /quotas/{subscription key})

    2. Use Client ID, client secret & tenant ID generated from above step to call this API https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token with body type x-www-form-urlencoded and body key value as below

      KEY: grant_type VALUE: client_credentials

      KEY: client_id VALUE: appid generated from step number 1

      KEY: scope VALUE: https://management.azure.com/.default

      KEY: client_secret VALUE: password generated from step number 1

    Then use the output access token to get quota policy consumption.