azure-api-managementazure-policy

Adding query parameter by checking Subscription key in APIM policy


In APIM, for a Restful API, I want to add a query parameter by checking the subscription key. i.e Consumer A has subscription key "43434-4545435-dfdfgfdg" in the APIM policy, I want to check the Subscription key and add a query parameter like ?user=consumerA

What would be the convenient way to achieve that?


Solution

  • There are a few ways to achieve what you want, my suggestion would be to pass the entire context through to your API so you have access to everything you need and only need to send it once.

    You need to add it to an inbound policy.

    You can pass the entire context through as a header parameter ...

    <set-header name="x-apim-context-subscription" exists-action="override">
        <value>@(JsonConvert.SerializeObject(context.User))</value>
    </set-header>
    

    ... however, to achieve the specific outcome you're looking for, you can always do something like this ...

    <set-query-parameter name="user" exists-action="override">
        <value>@(context.User.Id)</value>
    </set-query-parameter>
    

    You'd need to consult the documentation to ensure you get exactly what you want, it may be the you need to refer to the Subscription object within the context instead of User.

    https://learn.microsoft.com/en-us/azure/api-management/api-management-policy-expressions