Create custom json from response

Friends I am new at Apigee but aware about basic concepts.

We have requirement like if we get response from client at apigee for example.

{
"headers": {
"Accept": "text/html"
},
"origin": "203.99.214.107"
}

we need to process above json and in response we need to send something like below

[{
"body": "{\n\t\"headers\": {\n\t\t\"Accept\": \"text/html\"\n\t},\n\t\"origin\": \"203.99.214.107\"\n}"
}]

Please mind I have just escaped example json and puts within " " of below json

[{"body":""}]

Do I need to write some custom Java/python callout for this or we can do it at Apigee itself.

As I think for escape/unscape json content we have to write java/python callout but for adding this [{"body":""}] in response. Is there any policy combination I can use.

1 3 3,181
3 REPLIES 3

Well generally we can use Assign Message policy to set the response like,

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true" name="Assign-Message-1">
    <DisplayName>Assign Message-1</DisplayName>
    <Properties/>
    <Set>
        <Payload contentType="application/json">
           {
           "body":{response.content}
           }
       </Payload>
    </Set>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <AssignTo createNew="false" transport="http" type="request"/>
</AssignMessage>

Why do you want to escape JSONcontent completely?

If you have Message Template option enable for your org, you can also look at escapeJSON,

https://docs.apigee.com/api-platform/reference/message-template-intro#example-escapejson

I guess you will be interested in JS,

var backendResponJSON = context.getVariable("response.content");
var EscapedJSONString = JSON.stringify(backendResponJSON, null, "\r\t");


context.setVariable("escapedResponse",JSON.stringify(EscapedJSONString))

// logic to send JSON response - constructing response //

finalResponse.body = context.getVariable('escapedResponse');

or after escaping the JSON you can use Assign Message policy to send the final response.

Be aware, you can also use the escapeJSON() function in the message template.

<AssignMessage name="Assign-Message-1">
    <Set>
        <Payload contentType="application/json">{
  "body":{escapeJSON(response.content)}
}
</Payload>
    </Set>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <AssignTo>response</AssignTo>
</AssignMessage>

Using that builtin function , you could eliminate the JavaScript.

Thanks @Dino-at-Google and @Siddharth Barahalikar

Both of your answers helped a lot to me. Thank you very much.