Get the Names of Sites Running in Crafter Engine and Return it them as JSON

From time to time developers want to be able to get a list of tenants on a given Crafter Engine.  A tenant is equivalent to a project in Crafter.  That project may be a website, a content app, a headless content API or any one of 1000 different kinds of digital experience.  Usually, when people want to get a list of the active tenants on a server it’s to assist with some kind of DevOps automation of site creation and management.  In this example, we create a simple RESTful service that returns the list of sites running in Crafter Engine. You can find the API for the Context Manager HERE

Step 1: Create a REST Controller

  • In a Crafter Studio project, Under Scripts/rest right click and click “create controller.”
    • Enter “get-sites.get” as the controller name
  • Add the following code to the controller.
def siteContextManager = applicationContext["crafter.siteContextManager"]
def siteContextList = siteContextManager.listContexts()
def siteNames = []

siteContextList.each { siteContext ->
    def name = siteContext.getSiteName()
    siteNames.add(name)
}

return siteNames

Step 2: Execute the Service