Custom scripting service example

From DreamFactory
Jump to: navigation, search
DreamFactoryTutorialsCustom scripting service example


You can create any number of custom scripting services and invoke them from the REST API. In this example we'll create a simple service named 'math' that accepts two numbers as query parameters and returns the result as JSON. Since the script is a service, you can control access to it using roles. The script has whatever access to the API that is allowed by the role of the user calling the script. If allowed, the script can make additional REST API calls or cURL requests.

Create a PHP custom scripting service

  • Go to the services tab in the admin console and click Create.
  • Set the Service Type to Custom Scripting Service.
  • Set the service name to 'math'.
  • Set the service label to 'Math'.
  • Go to the Config tab for the new service and set the Script Engine Type to PHP.
  • Set the Content to contain the following code then click Create Service.

$verb = $event['request']['method'];

if($verb !== 'GET'){
    throw new \DreamFactory\Core\Exceptions\BadRequestException('Only HTTP GET is allowed on this endpoint.');

// get resource, /math —> "", /math/add —> "add"
$resource = $event['resource'];

// get query params from request
$params = $event['request']['parameters'];

$required = ['n1', 'n2'];

    foreach($required as $element){
            throw new \DreamFactory\Core\Exceptions\BadRequestException('Missing '.$element.' in params.');
    $n1 = $params['n1'];
    $n2 = $params['n2'];

switch ($resource) {
    case "":
        // /math means return all supported resources
        $result = ['resource' => ['add', 'subtract', 'multiply', 'divide']];
    case "add":
        $result = ['result' => ($n1 + $n2)];
    case "subtract":
        $result = ['result' => ($n1 - $n2)];
    case "multiply":
        $result = ['result' => ($n1 * $n2)];
    case "divide":
        if (!$n2) {
            throw new \DreamFactory\Core\Exceptions\BadRequestException('Divide by zero error.');
        $result = ['result' => ($n1 / $n2)];
        throw new \DreamFactory\Core\Exceptions\BadRequestException('Invalid or missing resource name.');

return $result;

Call the service

From any REST client, make the request GET /api/v2/math/add?n1=4&n2=5 and you should get back the result of 9. A simple REST client can be found at <your_instance_url>/test_rest.html. Remember if you are not an admin user your user role must allow access to the custom scripting service.