How do I extract and match values inside APIM management policy

Gregory Suvalian 5 Reputation points
2025-01-23T20:26:02.02+00:00

Hello,

I have JSON array in form below

[
  {
    "hostname": "hostname1.company.com",
    "value": 28
  },
  {
    "hostname": "hostname2.company.com",
    "value": 55
  }
]

This is stored on external URL and retrieved during policy run and put into cache.

I need to extract value from this array matching to incoming hostheader of request and having trouble writing correct Azure APIM Policy to do that

<inbound>
        <cache-lookup-value key="hostnames" variable-name="hostnames" />
        <choose>
            <when condition="@(!context.Variables.ContainsKey("hostnames"))">
                <send-request mode="new" response-variable-name="response" timeout="20" ignore-error="true">
                <set-url>@($"https://gist.githubusercontent.com/artisticcheese/b72ecad52e5c6804c7f0e81dd0344dc7/raw/908bf7f93891674ca665d3c4982a02de43b6ed6f/gistfile1.txt")</set-url>

                    <set-method>GET</set-method>
                </send-request>
                <set-variable name="hostnames" value="@(((IResponse)context.Variables["response"]).Body.As<JObject>())" />
                <cache-store-value key="hostnames" value="@((string)context.Variables["hostnames"])" duration="100000" />
            </when>
        </choose>
        <set-variable name="requestHostname" value="@(context.Request.Headers["X-Forwarded-Host"].First())" />
        <set-variable name="matching_value" value="@{ 
          var inputJson = context.Variables["hostnames"];
    var incomingHostheader = context.Variables["requestHostname"];  
    var jsonArray = (JArray)inputJson;
 var matchedEntry = jsonArray.FirstOrDefault(entry => 
                (string)entry["hostname"] == incomingHostheader );
                return matchedEntry;
}" />
        <return-response>
            <set-status code="200" reason="OK" />
            <set-header name="Content-Type" exists-action="override">
                <value>application/json</value>
            </set-header>
            <set-body>@{
        var hostnames = (string)context.Variables["hostnames"];
        return hostnames;
    }</set-body>
        </return-response>
        <base />
    </inbound>

Code does not work, it's probably easier to do compared to what I did so far

Azure API Management
Azure API Management
An Azure service that provides a hybrid, multi-cloud management platform for APIs.
2,271 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.