简体   繁体   English

Azure APIM 中的响应映射

[英]Response mapping in Azure APIM

Is there any way which can map my response of API into the required format in azure APIM有什么方法可以将我对 API 的响应映射到 azure APIM 中所需的格式

eg if my API gave a response like例如,如果我的 API 给出了类似的响应

customer:  {
"id" : 123
}

the output I will be needing is我需要的输出是

customer: {
"customerID": 123
} 

Is there any way without using a set-body policy?有没有不使用 set-body 策略的方法? or is there any way where I can define logic which can map Id value to customerID或者有什么方法可以定义可以将Id值映射到customerID逻辑

您可以使用Find and Replace String in Body策略来获得简单的解决方案。

There are two options:有两种选择:

Simple JSON简单的 JSON

If you have simple JSON as you have shown in the question, then Find and Replace transformation policy can be helpful.如果您有问题中所示的简单 JSON,则查找和替换转换策略可能会有所帮助。 Please note that this policy would just perform string replace.请注意,此策略只会执行字符串替换。 It does not know anything about JSON format.它对 JSON 格式一无所知。 So you have to be extra careful while replacing anything.所以你在更换任何东西时都必须格外小心。

But I assume the JSON might not be that simple in real world scenarios.但我认为 JSON 在现实世界中可能没有那么简单。

Complex JSON复杂的 JSON

You can implement your custom logic by using Set Body Transformation Policy.您可以使用Set Body Transformation Policy 来实现您的自定义逻辑。

Code would be something like below.代码如下所示。 You can get the JObject and then query and update it.您可以获取 JObject,然后对其进行查询和更新

<choose>
  <when condition="@(context.Response.StatusCode == 200"> 
    <set-body> 
    @{ 
        JObject inBody = context.Request.Body.As<JObject>();

        // Razor view syntax so you can write code as per your need
        JObject customer= (JObject)inBody["customer"];
        var customerIdValue = ((string)customer["id"]);
        customer["CustomerId"] = customerId;

        customer.Property("id").Remove();

        // assuming customer has a description property
        customer.Property("description").AddAfterSelf(new JProperty("customerId", customerIdValue));
        return inBody.ToString(); 
    } 
    </set-body>
  </when>
</choose>

Could also use set-body with liquid template in outbound of your operation:还可以在操作的出站中使用带有液体模板的 set-body:

<set-body template="liquid">{
    "customer": {
        "customerID": {{body.customer.id}}
    }
}</set-body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM