azure-api-management

Access the JSON property from JSON Response - Azure APIM Policies


If I am getting below JSON response from an API, how can I get the status and code properties in that.

{
  "error": {
    "status": 0,
    "code": "string",
    "message": "string",
    "target": "string",
    "instance": "string",
    "details": [
      "string"
    ]
  }
}

Below is my policy code which is currently in place.

<policies>
    <inbound>
        <base />
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
        <set-variable name="errorResponse" value="@(context.Response.Body.As<JObject>()["error"])" />
        <choose>
            <when condition="@(context.Variables["errorResponse"]!=null)">
                <set-variable name="errorStatus" value="@{
                    var jsonObject = JObject.Parse(context.Response.Body.As<JObject>()["error"]);
                    var value = (string)jsonObject["status"];
                    return value;
                }" />
                <set-variable name="errorStatus" value="@{
                    var jsonObject = JObject.Parse(context.Response.Body.As<JObject>()["error"]);
                    var value = (string)jsonObject["code"];
                    return value;
                }" />
                <choose>
                    <when condition="@((int)context.Variables["errorStatus"]==404)">
                        <return-response>
                            <set-status code="200" reason="NotFound" />
                            <set-body template="liquid">
                                { 
                                    "status": "NotFound"
                                }
                            </set-body>
                        </return-response>
                    </when>
                </choose>
            </when>
        </choose>
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

I am expecting to get the value of status and code json properties from the outbound response.


Solution

  • If you need to access the status and code properties from the API response in your policy code, the following should work:

    <set-variable name="ResponseBody" value="@(context.Response.Body?.As<JObject>(preserveContent: true))" />
    <set-variable name="ErrorStatus" value="@{
        var responseBody = context.Variables.GetValueOrDefault<JObject>("ResponseBody");
        return (int)responseBody["error"]["status"];
    }" />
    <set-variable name="ErrorCode" value="@{
        var responseBody = context.Variables.GetValueOrDefault<JObject>("ResponseBody");
        return (string)responseBody["error"]["code"];
    }" />