In the course of business, it is inevitable that you might require a custom REST endpoint that delivers content in a particular format or even to deliver a subset of content and related content in a JSON graph.
These examples are perfect cases for using Velocity to generate a complex JSON response that can be consumed by other apis. The beauty of these endpoints is that they can leverage the front end tooling embedded in dotCMS which has been tuned for performance. They can also leverage the page caching native to dotCMS Enterprise.
The strategy to use Velocity as a REST endpoint today is:
Below is an example of a .vtl file being used to deliver a custom JSON response.
$response.setContentType("application/json")
#set($page = $dotcontent.find("xxxxxx-xxxxxx-xxxxxx-xxxxxx") ##pass the identifier of the page
## GET AN EMPTY MAP
#set($map = {})
## GET AN EMPTY ARRAY
#set ($fields = [])
#set ($d = $!fields.add("name"))
#set ($d = $!fields.add("link"))
#foreach($field in $fields)
#set($item = {})
$!item.put($field,${page.get("$field")})
$!map.put("$field",$item)
#end
#set ($d = $!fields.add("image"))
#set($item = {})
#set ($d = $!item.put("image",${page.image.file.name}))
#set ($d = $!map.put("image",$item))
#set($item = {})
#set($item_es = {})
#foreach($con in $dotcontent.pullRelated("Company-Text",${page.identifier},false,100))
#set ($d = $item.put($con.key,$con.value))
#if($text.get("$con.key","es-es"))
#set ($d = $item_es.put("$con.key",$text.get($con.key,"es-es")))
#end
#end
#set ($d = $!map.put("text",$item))
#set ($d = $!map.put("text_es",$item_es))
#set($item = {})
#set($item_es = {})
#foreach($con in $dotcontent.pullRelated("Company-Errors",${page.identifier},false,100))
#set ($d = $item.put($con.key,$con.value))
#if($text.get("$con.key","es-es"))
#set ($d = $item_es.put("$con.key",$text.get($con.key,"es-es")))
#end
#end
#set ($d = $!map.put("errors",$item))
#set ($d = $!map.put("errors_es",$item_es))
#set($topMap = {})
#set ($d = $!topMap.put("Contents",$map))
$json.generate($topMap)