'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 1:[1]

As per the Azure Documentation, You can set rate-limit by subscription only in inbound section & the policy scope should be either product, api or operation.

Here is the sample example, where the per subscription rate limit is 30 calls per 90 seconds. After each policy execution, the remaining calls allowed in the time period are stored in the variable remainingCallsPerSubscription.

<policies>
    <inbound>
        <base />
        <rate-limit calls="30" renewal-period="90" remaining-calls-variable-name="remainingCallsPerSubscription"/>
    </inbound>
    <outbound>
        <base />
    </outbound>
</policies>

Note: This policy can be used only once per policy document.

Policy expressions cannot be used in any of the policy attributes for this policy.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 VenkateshDodda-MSFT