MarkLogic

Script a MarkLogic REST Server in xquery

This is just a quick one, mainly in case I forget, but if you happen to be trying to script the creation of a REST server on top of a MarkLogic database using the Admin module, you might be wondering how to turn the http service they setup in the examples into an actual REST server. Well the trick is to have a poke around the MarkLogic files until you stumble upon /MarkLogic/Modules/MarkLogic/rest-api/lib/bootstrap-util.xqy. This little bit of xquery contains a function util:bootstrap-rest-server which basically runs the standard http server setup stuff, but then has 7 magic lines

let $appserver-id := admin:appserver-get-id($config, $groupid, $rest-appserver-name)
let $config := admin:appserver-set-url-rewriter($config, $appserver-id, "/MarkLogic/rest-api/rewriter.xqy")
let $config := admin:appserver-set-error-handler($config,$appserver-id, "/MarkLogic/rest-api/error-handler.xqy")
let $config := admin:appserver-set-authentication($config, $appserver-id, "digest")
let $config := admin:appserver-set-log-errors($config, $appserver-id, false())
let $config := admin:appserver-set-rewrite-resolves-globally($config, $appserver-id, true())
let $config := admin:database-set-directory-creation($config, xdmp:database( $rest-db-modules-name ), "automatic")

So your creation script can either potentially just call this function (although I haven’t tried it), but we wanted to create a REST server using the file system as our Module store, so I just modified our script to this:

xquery version "1.0-ml";
import module namespace admin = "http://marklogic.com/xdmp/admin"
  at "/MarkLogic/admin.xqy";

let $GroupName := "Default"
let $ServiceName := "MyRestServer"
let $DocumentDir := "MyRestServerRoot/"
let $ServicePort := 8003
let $Database := "MyDatabase"

let $config := admin:get-configuration()

let $groupid := admin:group-get-id($config, $GroupName)

let $config := admin:http-server-create(
    $config,
    $groupid,
    $ServiceName,
    $DocumentDir,
    $ServicePort,
    "file-system",
    admin:database-get-id($config, $Database))
 
let $appserver-id := admin:appserver-get-id($config, $groupid, $ServiceName)
let $config := admin:appserver-set-url-rewriter($config, $appserver-id, "/MarkLogic/rest-api/rewriter.xqy")
let $config := admin:appserver-set-error-handler($config,$appserver-id, "/MarkLogic/rest-api/error-handler.xqy")
let $config := admin:appserver-set-authentication($config, $appserver-id, "digest")
let $config := admin:appserver-set-log-errors($config, $appserver-id, false())
let $config := admin:appserver-set-rewrite-resolves-globally($config, $appserver-id, true())

return admin:save-configuration($config);

You may need to tweak your script for your specific scenario but at least now you know where to look

Advertisements