Himanshu
Himanshu

Reputation: 363

AWS API Gateway : Convert response to XML

I am getting a string value (xml to string) from lambda backend which should be returned to end user in application/xml format. How can I achieve this?

Upvotes: 6

Views: 7186

Answers (2)

Stuartb__
Stuartb__

Reputation: 21

With reference to this document, section "Accessing the $util Variable", solved the challenge in a simple JSON to XML transform. I did try the mapping template given earlier here, but it did not work for me.

In my case, my JSON response payload is of the form:

[
  {
    "key1": "val1",
    "key2": "val2",
    "key3": "val3"
  },
  {
    "key1": "val1",
    "key2": "val2",
    "key3": "val3",
    "key4": "val4"
  }
]

Here is the mapping template that deals with it:

#set ($arr = $util.parseJson($input.path('$')))
<responses>
#foreach($c in $arr)
    <response>
#foreach ($k in $c.keySet())
      <$k>$c.get($k)</$k>#end
    </response>
#end
</responses>

The key was the parseJson to get a true JSON/Java object. After thi it was smooth sailing.

And the output is of the form:

<responses>
    <response>
        <key1>val1</key1>
        ...
    </response>
    ...
</responses>

I hope this helps.

Upvotes: 1

James
James

Reputation: 11931

You can specify an Integration Response that returns XML, along with a mapping template to format XML using the object returned from Lambda.

Sample Integration Response

I do not believe there is a default format conversion to XML. A simple mapping template might be like this:

#set($root = $input.path('$'))
<stuff>
    <message>$root.message</message>
    <sourceIp>$context.identity.sourceIp</sourceIp>
    <outputs>
        #foreach($key in $root.keySet())
        <output>
            <key>$key</key>
            <value>$root.get($key)</value>
        </output>
        #end
    </outputs>
</stuff>

Upvotes: 6

Related Questions