Back

Using Velocity as a REST Endpont

Description

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:

  1. Create a folder to hold this these type of "endpoints", e.g. /endpoint
  2. Create a page with the “blank” template which acts as your endpoint, e.g. /endpoint/contentRelationhip
  3. Add a single velocity widget to that page that points to a .vtl file that contains the logic and outputs the custom json response.

Below is an example of a .vtl file being used to deliver a custom JSON response.  

Code

$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)

Have you created code you'd like to share with the dotCMS community?

Share your code Become a Contributor