astroboy
astroboy

Reputation: 53

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>  

Upvotes: 4

Views: 17692

Answers (1)

astaykov
astaykov

Reputation: 30893

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>  

Upvotes: 4

Related Questions