Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure API Management Service Set body Policy - modify JSON response to return certain fields

Based on

Azure API Management Service "Set body" Policy

We can modify the response of an API service. For Eg., instead of returning below :

{ 
  "company" : "Azure",
  "service" : "API Management"
}

We would only like to return :

{ "company" : "Azure" }

I am not sure how to accomplish this as I have no idea what kind of programming language / syntax they are using in their documentation as shown below :

<set-body>  
@{   
    string inBody = context.Request.Body.As<string>(preserveContent: true);   
    if (inBody[0] =='c') {   
        inBody[0] = 'm';   
    }   
    return inBody;   
}  
</set-body>  
like image 562
astroboy Avatar asked Oct 28 '25 06:10

astroboy


1 Answers

What you look at is called Policy expressions and is well described on the official documentation here. A short quote from the site states:

Policy expressions syntax is C# 6.0. Each expression has access to the implicitly provided context variable and an allowed subset of .NET Framework types.

A more appropriate sample in the set-body samples would be the one that filters output:

<!-- Copy this snippet into the outbound section to remove a number of data elements from the response received from the backend service based on the name of the api product -->  
    <set-body>@{  
        var response = context.Response.Body.As<JObject>();  
        foreach (var key in new [] {"minutely", "hourly", "daily", "flags"}) {  
          response.Property (key).Remove ();  
        }  
        return response.ToString();  
      }  
    </set-body>  

To customise that for your specific object - you want to remove the service property:

    <set-body>@{  
        var response = context.Response.Body.As<JObject>();  
        foreach (var key in new [] {"service"}) {  
          response.Property (key).Remove ();  
        }  
        return response.ToString();  
      }  
    </set-body>  
like image 141
astaykov Avatar answered Oct 30 '25 00:10

astaykov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!