Akana Platform Free Trial

Get Started Today »

Ian Goldsmith

One of the more important functions of an API Gateway is to create APIs that return well-structured content from existing services and resources that may not be the prettiest things you’ve ever seen.  A really common example is create a clean JSON document from data that is sourced from multiple backend SOAP services. This is where templating provides an ideal solution.

We happen to really like the Freemarker engine for a few reasons:

  • It’s the fastest of all the templating engines
  • It has an active user community on Stackoverflow
  • It’s very well documented
  • It handles extracting content from JSON and XML documents very efficiently
  • Did I mention that it’s blisteringly fast?

We have packaged Freemarker as a process activity that runs inside our Gateway, and have provided some documentation, samples and a simple little Freemarker template test tool on our public
Github repository – we’ll shortly be publishing the source code for the activity as well.

The beauty of Freemarker is how easy it is to create a piece of message content exactly how you want it to look and insert text into it from local variables or by pulling elements from existing content.  Something like this:

<br:add xmlns:br="http://demo.akana.com/borrower">
   <br:borrower>
      <br:id>${id}</br:id>
      <br:ssn>${ssn}</br:ssn>
      <br:first>${first}</br:first>
      <br:last>${last}</br:last>
   </br:borrower>
</br:add>

Or for json:

{ "borrower" : 
   { "id" : "${id}",
     "ssn" : "${ssn}",
     "first" : "${first}",
     "last" : "${last}"
   }
}

Of course, that’s all very well, but the real power comes in when you start introducing loops where you can iterate through elements in existing content to create a new document. We allow you to address elements in XML or JSON content very easily, for example:

<#assign m = message.contentAsString?eval>
{
  "name" : [
    <#list m as pet>
        "<#if pet.name??>${pet.name}<#else>${pet.category.name}</#if>"<#sep>,
    </#list>
  ]
}

Which uses the #list, #sep, and #if directives with the ?? operator to build a simple and yet powerful iterator.

Check it out on Github.  You might find the tools useful just to test your own Freemarker templates regardless of whether you’re using our products or not.  Some of the examples around JSON and XML content are very instructive.

Share Button

Add a comment