Scripting

From DreamFactory
Jump to: navigation, search
Line 1: Line 1:
== Supported Scripting Languages ==
+
DreamFactory supports server-side scripting to quickly and easily customize almost all of the platform's REST API endpoints to include business logic on the server, such as field validation, workflow triggers, runtime calculations and more. Developers can easily attach scripts to any existing API endpoint, for both pre- and post- processing of the request and response. You can also write your own custom REST APIs with our Custom Scripting Service type.
* [[DreamFactory/Features/Scripting/V8Js|V8Js]]
+
* [[DreamFactory/Features/Scripting/NodeJs|Node.Js]]
+
* [[DreamFactory/Features/Scripting/PHP|PHP]]
+
  
== Where Scripts Can Be Used ==
+
== What Resources Are Available To A Script ==
* [[DreamFactory/Features/Scripting/Events|System Events Scripting]]
+
* [[DreamFactory/Features/Scripting/Services|Custom Scripted Services]]
+
  
== Objects Available ==
+
When a script is executed, DreamFactory passes in two very useful resources that allow each script to access many parts of the system including system states, configuration and even a means to call other services or external APIs. They are the '''''event''''' resource and the '''''platform''''' resource.
  
DreamFactory passes in two additional objects for use in the scripts.
+
  '''Note:''' The term "resource" is used generically here, based on the scripting language used, the resource could either be an object (i.e. V8js or Node.js) or an array (i.e. PHP).
  
=== The Event Object ===
+
=== The Event Resource ===
  
The '''event''' object contains the structured data about the event triggered ([[DreamFactory/Features/Scripting/Events|System Events Scripting]]) or from the API service call ([[DreamFactory/Features/Scripting/Services|Custom Scripted Services]]).
+
The '''event''' resource contains the structured data about the event triggered ([[DreamFactory/Features/Scripting/Events|System Events Scripting]]) or from the API service call ([[DreamFactory/Features/Scripting/Services|Custom Scripted Services]]). As seen below, this include things like the request and response information available to this "event".
  
'''Note:''' Of all the variables provided to your script, only this '''event''' container object is writable.
+
  '''Note:''' Determined by the type of event triggering the script, parts of this '''event''' resource are writable. Modifications to this resource while executing the script will result in a change to that resource (i.e. request or response) in further internal handling of the API call.
  
==== Properties ====
+
The '''event''' resource has the following properties:
 
+
The '''event''' object has the following properties:
+
  
 
{|
 
{|
 
!Property||Type||Description
 
!Property||Type||Description
 
|-
 
|-
| `event.request` || object || An object representing the inbound REST API call, i.e. the HTTP request.
+
| '''request''' || resource || A resource representing the inbound REST API call, i.e. the HTTP request.
 
|-
 
|-
| `event.response` || object || An object containing the response to an inbound REST API call, i.e. the HTTP response.
+
| '''response''' || resource || A resource representing the response to an inbound REST API call, i.e. the HTTP response.
 
|-
 
|-
| `event.resource` || string || Any additional resource names typically represented as a replaceable part of the path, i.e. table name on a db/_table/{table_name} call.
+
| '''resource''' || string || Any additional resource names typically represented as a replaceable part of the path, i.e. "table name" on a db/_table/{table_name} call.
 
|}
 
|}
  
The `event.request` object contains all the components of the original HTTP request.
+
==== Event Request ====
 +
 
 +
The "request" resource contains all the components of the original HTTP request.
 +
This resource is always available, and is writable during pre-process event scripting.
 +
 
 
{|
 
{|
 
!Property||Type||Description
 
!Property||Type||Description
 
|-
 
|-
| `api_version` || string || The API version used for the request (i.e. 2.0).
+
| '''api_version''' || string || The API version used for the request (i.e. 2.0).
 
|-
 
|-
| `method` || string || The HTTP method of the request (i.e. GET, POST, PUT).
+
| '''method || string || The HTTP method of the request (i.e. GET, POST, PUT).
 
|-
 
|-
| `parameters` || object || An array of query string parameters received with the request.
+
| '''parameters''' || resource || An object/array of query string parameters received with the request, indexed by the parameter name.
 
|-
 
|-
| `headers` || object || The HTTP headers from the request.
+
| '''headers''' || resource || An object/array of HTTP headers from the request, indexed by the lowercase header name.
 
|-
 
|-
| `payload` || object || The body (POST body) of the request converted to an object, i.e. the `content` below presented as internally useable object.
+
| '''content''' || string || The body of the request in raw string format.
 
|-
 
|-
| `content` || string || The body of the request in raw string format.
+
| '''content_type''' || string || The format type (i.e. "application/json") of the raw '''content''' of the request.
 
|-
 
|-
| `content_type` || string || The format type (i.e. json) of the raw `content` of the request.
+
| '''payload''' || resource || The body (POST body) of the request, i.e. the '''content''', converted to an internally usable object/array if possible.
 +
|-
 +
| '''content_changed''' || boolean || Set this to true to copy the content back into the event handling stream on pre-process scripts.
 
|}
 
|}
  
Any changes to this data will overwrite existing data in the response, before further listeners are called and/or the request completes.
+
Any changes to this data will overwrite existing data in the request, before further listeners are called and/or the request completes.
 +
 
 +
==== Event Response ====
  
In `event.response` object contains the data being sent back to the client from the request.  
+
The '''response''' resource contains the data being sent back to the client from the request.
  
'''Note:''' This object is only available/relevant on '''post_process''' event scripts, and Custom Scripting service scripts.
+
  '''Note:''' This resource is only available/relevant on '''post-process''' event scripts, and Custom Scripting service scripts.
 
{|
 
{|
 
!Property||Type||Description
 
!Property||Type||Description
 
|-
 
|-
| `api_version` || string || The API version used for the request (i.e. 2.0).
+
| '''status_code''' || integer || The HTTP status code of the response (i.e. 200, 404, 500, etc).
 
|-
 
|-
| `status_code` || integer || The HTTP status code of the response (i.e. 200, 404, 500, etc).
+
| '''headers''' || resource || An object/array of HTTP headers for the response back to the client.
 
|-
 
|-
| `headers` || object || The HTTP headers from the request.
+
| '''content''' || mixed || The body of the request as an object if the '''content_type''' is not set, or in raw string format.
 
|-
 
|-
| `content` || mixed || The body of the request as an object if the `content_type` is not set, or in raw string format.
+
| '''content_type''' || string || The content type (i.e. json) of the raw '''content''' of the request.
 
|-
 
|-
| `content_type` || string || The content type (i.e. json) of the raw `content` of the request.
+
| '''content_changed''' || boolean || Set this to true to copy the content back into the event handling stream on post-process scripts.
 
|}
 
|}
  
Just like `event.request`, any changes to `event.response` will overwrite existing data in the response, before it is sent back to the client.  
+
Just like '''request''', any changes to '''response''' will overwrite existing data in the response, before it is sent back to the client.
  
=== The Platform Object ===
+
=== The Platform Resource ===
  
'''Note:''' The `platform` object is only available in V8Js scripts currently.
+
This '''platform''' resource may be used to access configuration and system states, as well as, the REST API of your instance via '''inline''' calls.
 +
This make internal requests to other services directly without requiring an HTTP call.
  
This '''platform''' object may be used to access the REST API of your instance via '''inline''' calls. This make service requests directly without requiring an HTTP call.
+
The '''platform''' resource has the following properties:
The '''platform''' object has the following properties:
+
 
{|
 
{|
 
! Field || Type || Description
 
! Field || Type || Description
 
|-
 
|-
| `platform.api` || object || An object that allows access to the instance's REST API
+
| '''api''' || resource || An array/object that allows access to the instance's REST API.
 
|-
 
|-
| `platform.config` || object || The current configuration of the instance
+
| '''config''' || resource || An array/object consisting of the current configuration of the instance.
 
|-
 
|-
| `platform.session` || object || The current session information
+
| '''session''' || resource || An array/object consisting of the current session information.
 
|}
 
|}
  
These  `platform.api` object contains methods for instance API access. This object contains a method for each type of REST verb.
+
==== Platform API ====
 +
 
 +
The '''api''' resource contains methods for instance API access. This object contains a method for each type of REST verb.
 +
 
 +
'''Note:''' This doesn't currently work for Node.js.
 +
 
 
{|
 
{|
! Function || Description  
+
! Function || Description
 
|-
 
|-
| `platform.api.get` || GET a resource
+
| '''get''' || GET a resource
 
|-
 
|-
| `platform.api.post` || POST a resource
+
| '''post''' || POST a resource
 
|-
 
|-
| `platform.api.put` || PUT a resource
+
| '''put''' || PUT a resource
 
|-
 
|-
| `platform.api.patch` || PATCH a resource
+
| '''patch''' || PATCH a resource
 
|-
 
|-
| `platform.api.delete` || DELETE a resource
+
| '''delete''' || DELETE a resource
 
|}
 
|}
  
Line 106: Line 112:
  
 
<source lang="javascript">
 
<source lang="javascript">
platform.api.get( "service[/resource[/resource_id]]"[, payload] );
+
method( "service[/resource_path]"[, payload[, curl_options]] );
 
</source>
 
</source>
  
* `service` is always required.
+
* '''method''' - Required. The method/verb listed above.
* `resource` and `resource_id` are optional and depend on your call.
+
* '''service''' - Required. The service name (as used in API calls) or external URI.
* `payload` is optional, but must contain a valid object for the language of the script.  
+
* '''resource_path''' - Optional depending on your call. Resources of the service called.
 +
* '''payload''' - Optional, but must contain a valid object for the language of the script.
 +
* '''curl_options''' - Optional for external calls only.
  
You may also pass absolute URLs to these methods to retrieve external resources:
+
Calling internally only requires the relative URL sans the '''/api/v2/''' portion:
  
 
<source lang="javascript">
 
<source lang="javascript">
var _page = platform.api.get( "http://www.google.com" );
+
// Retrieve all records from the 'Contacts' table in the 'db' database service
 +
platform.api.get( "db/_table/Contacts" );
 
</source>
 
</source>
  
or
+
You may also pass absolute URLs to these methods to retrieve external resources:
  
 
<source lang="javascript">
 
<source lang="javascript">
var _result = platform.api.get( "https://www.example.com/api/something_cool", {"cool":"very"} );
+
platform.api.get( "http://www.google.com" );
 
</source>
 
</source>
  
Calling internally however only requires the relative URL sans the `/api/v2/` portion:
+
or
  
 
<source lang="javascript">
 
<source lang="javascript">
// Retrieve all records from the 'Contacts' table in the 'db' database service
+
platform.api.post( "https://www.example.com/api/something_cool", {"cool":"very"} );
var _records = platform.api.get( "db/_table/Contacts" );
+
 
</source>
 
</source>
  
==== Adding headers or other cURL options to platform.api calls ====
 
  
You can include an optional third argument to add cURL options to the request. For example to add headers
+
===== Adding headers or other cURL options to '''api''' calls =====
 +
 
 +
For example to add headers
  
 
<source lang="javascript">
 
<source lang="javascript">
Line 141: Line 150:
 
};
 
};
  
result = platform.api.post("http://localhost/rest/db/todo", JSON.stringify({"name":"test"}), options);
+
result = platform.api.post("http://example.com/my_api", {"name":"test"}, options);
 
</source>
 
</source>
  
  Please note the double quotation marks around the `CURLOPT_*` constant names. Unlike PHP, this is required in Javascript.  
+
  '''Note:''' The double quotation marks around the '''CURLOPT_*''' constant names are required in Javascript, unlike PHP.
  
 
You can also add multiple cURL options like this.
 
You can also add multiple cURL options like this.
Line 154: Line 163:
 
};
 
};
  
result = platform.api.post("http://localhost/rest/db/todo", JSON.stringify({"name":"test"}), options);
+
result = platform.api.post("http://example.com/my_api", null, options);
 
</source>
 
</source>
  
For GET you can set the second argument, payload, to null to include the optional third argument for the cURL options.
+
==== Platform Config ====
  
<source lang="javascript">
+
The '''config''' object contains configuration settings for the instance.
var options = {
+
    "CURLOPT_HTTPHEADER": ["Content-type: application/json", "Some-Other-Header: blah"]
+
};
+
  
result = platform.api.get("http://localhost/rest/db/todo", null, options);
+
{|
</source>
+
! Function || Description
 +
|-
 +
|}
 +
 
 +
==== Platform Session ====
 +
 
 +
The '''session''' resource contains information and states about the current session for the event.
 +
 
 +
{|
 +
! Function || Description
 +
|-
 +
| '''api_key''' || DreamFactory API key.
 +
|-
 +
| '''session_token''' || Session token, i.e. JWT.
 +
|-
 +
| '''user''' || User information derived from the supplied session token, i.e. JWT.
 +
        (
 +
            [id] => 6
 +
            [display_name] => First Last
 +
            [first_name] => First
 +
            [last_name] => Last
 +
            [email] => first.last@company.com
 +
            [is_sys_admin] => 1
 +
            [last_login_date] => 2016-02-19 14:05:25
 +
        )
 +
|-
 +
| '''app''' || App information derived from the supplied API key.
 +
|-
 +
| '''lookup''' || Available lookups for the session.
 +
|}
 +
 
 +
 
 +
== Supported Scripting Languages ==
 +
* [[DreamFactory/Features/Scripting/V8Js|V8Js]]
 +
* [[DreamFactory/Features/Scripting/NodeJs|Node.Js]]
 +
* [[DreamFactory/Features/Scripting/PHP|PHP]]
 +
 
 +
== Where Scripts Can Be Used ==
 +
* [[DreamFactory/Features/Scripting/Events|System Events Scripting]]
 +
* [[DreamFactory/Features/Scripting/Services|Custom Scripted Services]]

Revision as of 21:33, 22 February 2016

DreamFactory supports server-side scripting to quickly and easily customize almost all of the platform's REST API endpoints to include business logic on the server, such as field validation, workflow triggers, runtime calculations and more. Developers can easily attach scripts to any existing API endpoint, for both pre- and post- processing of the request and response. You can also write your own custom REST APIs with our Custom Scripting Service type.

What Resources Are Available To A Script

When a script is executed, DreamFactory passes in two very useful resources that allow each script to access many parts of the system including system states, configuration and even a means to call other services or external APIs. They are the event resource and the platform resource.

 Note: The term "resource" is used generically here, based on the scripting language used, the resource could either be an object (i.e. V8js or Node.js) or an array (i.e. PHP).

The Event Resource

The event resource contains the structured data about the event triggered (System Events Scripting) or from the API service call (Custom Scripted Services). As seen below, this include things like the request and response information available to this "event".

 Note: Determined by the type of event triggering the script, parts of this event resource are writable. Modifications to this resource while executing the script will result in a change to that resource (i.e. request or response) in further internal handling of the API call.

The event resource has the following properties:

Property Type Description
request resource A resource representing the inbound REST API call, i.e. the HTTP request.
response resource A resource representing the response to an inbound REST API call, i.e. the HTTP response.
resource string Any additional resource names typically represented as a replaceable part of the path, i.e. "table name" on a db/_table/{table_name} call.

Event Request

The "request" resource contains all the components of the original HTTP request. This resource is always available, and is writable during pre-process event scripting.

Property Type Description
api_version string The API version used for the request (i.e. 2.0).
method string The HTTP method of the request (i.e. GET, POST, PUT).
parameters resource An object/array of query string parameters received with the request, indexed by the parameter name.
headers resource An object/array of HTTP headers from the request, indexed by the lowercase header name.
content string The body of the request in raw string format.
content_type string The format type (i.e. "application/json") of the raw content of the request.
payload resource The body (POST body) of the request, i.e. the content, converted to an internally usable object/array if possible.
content_changed boolean Set this to true to copy the content back into the event handling stream on pre-process scripts.

Any changes to this data will overwrite existing data in the request, before further listeners are called and/or the request completes.

Event Response

The response resource contains the data being sent back to the client from the request.

 Note: This resource is only available/relevant on post-process event scripts, and Custom Scripting service scripts.
Property Type Description
status_code integer The HTTP status code of the response (i.e. 200, 404, 500, etc).
headers resource An object/array of HTTP headers for the response back to the client.
content mixed The body of the request as an object if the content_type is not set, or in raw string format.
content_type string The content type (i.e. json) of the raw content of the request.
content_changed boolean Set this to true to copy the content back into the event handling stream on post-process scripts.

Just like request, any changes to response will overwrite existing data in the response, before it is sent back to the client.

The Platform Resource

This platform resource may be used to access configuration and system states, as well as, the REST API of your instance via inline calls. This make internal requests to other services directly without requiring an HTTP call.

The platform resource has the following properties:

Field Type Description
api resource An array/object that allows access to the instance's REST API.
config resource An array/object consisting of the current configuration of the instance.
session resource An array/object consisting of the current session information.

Platform API

The api resource contains methods for instance API access. This object contains a method for each type of REST verb.

Note: This doesn't currently work for Node.js.
Function Description
get GET a resource
post POST a resource
put PUT a resource
patch PATCH a resource
delete DELETE a resource

They all accept the same arguments:

method( "service[/resource_path]"[, payload[, curl_options]] );
  • method - Required. The method/verb listed above.
  • service - Required. The service name (as used in API calls) or external URI.
  • resource_path - Optional depending on your call. Resources of the service called.
  • payload - Optional, but must contain a valid object for the language of the script.
  • curl_options - Optional for external calls only.

Calling internally only requires the relative URL sans the /api/v2/ portion:

// Retrieve all records from the 'Contacts' table in the 'db' database service
platform.api.get( "db/_table/Contacts" );

You may also pass absolute URLs to these methods to retrieve external resources:

platform.api.get( "http://www.google.com" );

or

platform.api.post( "https://www.example.com/api/something_cool", {"cool":"very"} );


Adding headers or other cURL options to api calls

For example to add headers

var options = {
    "CURLOPT_HTTPHEADER": ["Content-type: application/json", "Some-Other-Header: blah"]
};
 
result = platform.api.post("http://example.com/my_api", {"name":"test"}, options);
Note: The double quotation marks around the CURLOPT_* constant names are required in Javascript, unlike PHP.

You can also add multiple cURL options like this.

var options = {
    "CURLOPT_HTTPHEADER": ["Content-type: application/json", "Some-Other-Header: blah"],
    "CURLOPT_SOMEOTHEROPTION": "someothervalue"
};
 
result = platform.api.post("http://example.com/my_api", null, options);

Platform Config

The config object contains configuration settings for the instance.

Function Description

Platform Session

The session resource contains information and states about the current session for the event.

Function Description
api_key DreamFactory API key.
session_token Session token, i.e. JWT.
user User information derived from the supplied session token, i.e. JWT.
       (
           [id] => 6
           [display_name] => First Last
           [first_name] => First
           [last_name] => Last
           [email] => first.last@company.com
           [is_sys_admin] => 1
           [last_login_date] => 2016-02-19 14:05:25
       )
app App information derived from the supplied API key.
lookup Available lookups for the session.


Supported Scripting Languages

Where Scripts Can Be Used