JavaScript SDK
This page describes the Form.io JavaScript SDK
The JavaScript API is a minimalistic API library that allows you to work with the Form.io API's within your web application.
Installation
The Form.io SDK is part of our Open Source formio.js library which is found @ https://github.com/formio/formio.js. There are two ways to include the JavaScript SDK into your application.
Include using script tag
You can include it in a script tag within your application like the following shows.
Which would would then be able to do the following within your application.
Import into application
You can also import the SDK into your application as follows.
First perform an npm install
using the terminal application.
Then, you can import it into your application as follows.
Usage
Creating an instance of Formio is simple, and takes only a path (URL String). The path can be different, depending on the desired output. The Formio instance can also access higher level operations, depending on how granular of a path you start with.
Where endpoint is any valid API endpoint within Form.io. These URL's can provide a number of different methods depending on the granularity of the endpoint. This allows you to use the same interface but have access to different methods depending on how granular the endpoint url is.
The options (optional) is used to configure certain behaviors of the JavaScript API. The following options are available.
Property | Description | Example |
base | Allows you to override the base api url. | |
project | Allows you to override the project api url. | |
namespace | The namespace to store the localStorage variables. Defaults to formio | formio |
API Scopes
When using the JavaScript SDK, it is important to understand the different kinds of API scopes that are being queried via the API. The Form.io API is hierarchical which is also congruent with the JavaScript SDK when making API calls with the SDK. The following scopes are provided via the Form.io API / SDK (we will use "formio.com" as the hypothetical domain name you have deployed the Form.io platform against.
Scope | Description | Example API |
Root | This is the root or base URL for your Form.io deployment | https://formio.com |
Project | This is the API endpoint for a specific project | :rootScope/project/:projectId |
Form | This is the API endpoint for a specific | :projectScope/form/:formId |
Submission | This is the API endpoints for a specific submission | :formScope/submission/:submissionId |
Action | This is the API endpoints for specific action | :formScope/action/:actionId |
Role | This is the API endpoints for a specific role. | :projectScope/role/:roleId |
Project and Form Aliases
The Form.io API also uses aliases to make the use of the hierarchical API's easier to use. Currently, we provide alias support for both Projects and Forms, so that a typical Form URL would look like the following.
Where "formio.com" would be replaced with the URL of your deployment, "myproject" would be replaced with the alias name of your project, and "myform" would be replaced with the name of your form. All API endpoints within the examples below will use this URL format to demonstrate the different kinds of SDK methods.
Examples
If you wish to load the project JSON, or search for forms, you will instantiate as follows.
If you wish to load a specific submission.
Now that we understand how the SDK works, we can see all of the different API's available to the different API scopes as follows.
Static Methods
There are a few methods that are used statically, meaning that they do not require the new Formio
as the other methods require. These methods can be used as globals that are able to define the behavior of the JavaScript SDK and all instances created afterward. These methods are as follows.
Formio.setBaseUrl(baseUrl)
Formio.setBaseUrl(baseUrl)
Sets the Base URL of the renderer and SDK. This is a very important method that allows you to provide to the JavaScript SDK the Base Deployment URL of your API platform. This is always going to be the root URL of your deployment, which is also the same as the URL for the deployed developer portal application (if you have that enabled). The best way to know if you have this correct is that you should see the "status" of your deployment by going to :baseUrl/status
If this shows the version of the server, then you know this is the value of the base URL.
Example:
Formio.setProjectUrl(projectUrl)
Formio.setProjectUrl(projectUrl)
This is the Project URL that will be used to reference any Project endpoints within the SDK and renderer. This is also important to establish within your application to ensure that all relative urls are referencing the correct Project endpoints.
Example:
Formio.fetch(...)
Formio.fetch(...)
This method is a simple shim around the HTTP Fetch polyfill.
Formio.request(url, [method], [data], [header], [opts])
Formio.request(url, [method], [data], [header], [opts])
A static method to perform an API request to any REST API endpoint. This method is a simple wrapper around the JavaScript fetch method with the added handling of JWT tokens as well as implements a Caching mechanism for GET requests to ensure that multiple requests of the same nature do not constantly spam the API server. It's parameters are defined as follows.
Parameter | Description |
url | The URL you wish to send the request to. |
method (optional) | The method of the request. GET, PUT, POST, DELETE |
data (optional) | The data to include for PUT and POST requests |
header (optional) | An instance of the HTTP Header class to define headers for this request. |
opts (optional) | See Query Options |
Example: Send a request to fetch submissions.
Formio.makeStaticRequest(url, [method], [data], [opts])
Formio.makeStaticRequest(url, [method], [data], [opts])
This static method performs an API call to the Form.io API platform. This method is very similar to other request method but will also send the request through the Form.io fetch plugin to allow any fetch plugin to intercept the request being made. Its parameters are defined as follows.
Parameter | Description |
url | The URL you wish to send the request to. |
method (optional) | The method of the request. GET, PUT, POST, DELETE |
data (optional) | The data to include for PUT and POST requests |
opts (optional) | See Query Options |
Formio.setToken(token)
Formio.setToken(token)
Sets or removes the JWT token within localStorage.
Parmeter | Description |
token | A JWT token to set within localStorage. If the value of this parameter is empty, then the token will be deleted from localStorage. |
Formio.getToken()
Formio.getToken()
Retrieve the JWT token from localStorage.
Formio.setUser(user)
Formio.setUser(user)
Sets the User JSON object of the currently logged in user. This is the same JSON object that you would get if you sent an API request to /current
with your current JWT token. This user object is then stored within localStorage as formioUser
unless a different namespace
option is being used.
Parameter | Description |
user | The JSON of the user object that is fetched from the |
Formio.getUser()
Formio.getUser()
Fetch the user JSON object from the localStorage.
Formio.currentUser([formio], [opts])
Formio.currentUser([formio], [opts])
Fetch the current user via the /current
API endpoint.
Parameter | Description |
formio (optional) | An instance of the Formio SDK if necessary. |
opts (optional) | See Query Options |
Formio.accessInfo([formio])
Formio.accessInfo([formio])
Retrieves the access information for a specific project. You must ensure you set the project url using Formio.setProjectUrl()
before calling this method.
Parameter | Description |
formio (optional) | An instance of the Formio SDK if necessary. |
Formio.projectRoles([formio])
Formio.projectRoles([formio])
Retrieves the roles for a specific project. You must ensure you set the project url using Formio.setProjectUrl()
before calling this method.
Parameter | Description |
formio (optional) | An instance of the Formio SDK if necessary. |
Formio.clearCache()
Formio.clearCache()
Clears all the fetch caches to ensure that any future requests will retrieve fresh data from the API's.
Formio.logout([formio], [opts])
Formio.logout([formio], [opts])
Perform a logout against the Form.io API server.
Formio.pageQuery()
Formio.pageQuery()
Helper function to retrieve all of the URL query parameters in a javascript key-value pair mapped object.
Example: Given the following url
If you run this method on that page, it will return the following.
Formio.ssoInit([type], [options])
Formio.ssoInit([type], [options])
Initializes an SSO processes. This is used during SAML authentication processes to instantiate and continue a SAML SSO process.
Instantiate a SAML SSO process
Assuming that your project is configured for SAML, you can instantiate an SSO process by executing the following.
Process a SAML response
Once the SAML authentication returns to the application, you can process that response using the following.
The following parameters can be used.
Parameter | Description |
type | The type of SAML sso authentication to instantiate. Either "saml" or "okta" |
options | An object of options, which depends on the type. For saml type: - relay: This is the variable that will be provided to the relay of the sso process.
For okta type: - OktaAuth: An instance of the OktaAuth javascript object provided by Okta Javascript SDK - formio: An instance of the Form.io SDK. - scopes: A string of CSV scopes to apply |
Formio.requireLibrary(name, property, src, [polling])
Formio.requireLibrary(name, property, src, [polling])
Require an external JavaScript library for lazy-loading purposes.
Parameter | Description |
name | The name of the library |
property | The property that is added to the "window" object that indicates that the library has finished loading. For example, if you are wanting to load the "Lodash" library, the variable that is added to the window object is "_" |
src | The URL of the library you wish to load. |
polling | Creates a polling check to see if the library has finished loading. |
Formio.libraryReady(name)
Formio.libraryReady(name)
Returns a promise that will resolve once the library of the provided name is ready to be used.
Parameter | Description |
name | The name of the library to check if it is ready or not. |
Formio.loadProjects([query], [opts])
Formio.loadProjects([query], [opts])
A static method to load all projects within the configured baseUrl
of the SDK.
Parameter | Description |
query (optional) | See Query Options |
opts (optional) | See Fetch Options |
Formio.serialize(obj, [interpolate])
Formio.serialize(obj, [interpolate])
A method that will serialize a data map key-value pair object into a URL query string.
Parameter | Description |
obj | The object to serialize into a URL query string. |
interpolate (optional) | An optional interpolation method to interpolate certain values that are added. |
Project API Scope
The following API's are defined at the Project Scope. To instantiate the SDK at the project scope, you simply need to provide a Project API to the constructor as follows.
where "myproject" would be the alias name of your project. Once you have instantiated the SDK with the following URL, the following methods are now available to you at the Project Scope.
formio.loadProject([query], [opts])
formio.loadProject([query], [opts])
Loads the project using the following Project Load API
Parameter | Description |
query (optional) | See Query Options |
opts (optional) | See Fetch Options |
formio.saveProject(project, [opts])
formio.saveProject(project, [opts])
Creates or Updates a project depending on if the _id of the project is provided (upsert).
Example: Create a new project
Example: Update an existing project.
Parmameters | Description |
project | The project JSON you wish to create or update. If an "_id" is provided within the json, an update operation will be executed, otherwise it will create a new project. |
opts (optional) | See Fetch Options |
formio.deleteProject([opts])
formio.deleteProject([opts])
Deletes a project.
Parmameters | Description |
opts (optional) | See Fetch Options |
formio.loadForms([query], [opts])
formio.loadForms([query], [opts])
Loads all the forms within a project. This implements the List Forms API.
Parameter | Description |
query (optional) | See Query Options |
opts (optional) | See Fetch Options |
Example: List all Resources within a project, sort them based on created date, and only return the "title" and "path" of those forms
Example: List all Forms within a project, limit them to 20, and only return the "title" of those forms.
formio.getTempToken(expire, allowed, [options])
formio.getTempToken(expire, allowed, [options])
Retrieves a temporary auth token which can be used in conjunction with the PDF API's to download a PDF output of a submission.
formio.loadRoles([opts])
formio.loadRoles([opts])
Loads a list of roles for the provided project. Implements the List Roles API
Parameter | Description |
opts (optional) | See Fetch Options |
formio.getProjectId()
formio.getProjectId()
Returns the Project ID of the project in context, even if the URL provided to the constructor uses the project alias.
formio.accessInfo()
formio.accessInfo()
Retrieve the access information for a project. This method implements the Project Access Info API
formio.currentUser()
formio.currentUser()
Based on the JWT token stored within the localStorage, this method will retrieve the current user metadata and information.
Form API Scope
The following API's are available when the Form.io SDK is instantiated with the form scope like the following illustrates
formio.loadForm([query], [opts])
formio.loadForm([query], [opts])
Loads a form json
Parameter | Description |
query (optional) | See Query Options |
opts (optional) | See Fetch Options |
formio.saveForm(form, [opts])
formio.saveForm(form, [opts])
Creates or Updates a form depending on if an "_id" property is provided within the form json.
Parameter | Description |
form | The JSON of the form to save or update. If an "_id" is provided as a property of the form json, then an update operation is performed, otherwise, it will create a new form. |
opts (optional) | See Fetch Options |
Example: Create a new form
Example: Update an existing form
formio.deleteForm([opts])
formio.deleteForm([opts])
Deletes a form
Property | Description |
opts (optional) | See Fetch Options |
formio.getFormId()
formio.getFormId()
Returns the form Id of the form in context even if the form alias was provided for this form.
formio.loadSubmissions([query], [opts])
formio.loadSubmissions([query], [opts])
Loads a view of submissions for a form. This implements the Get Submissions API
Parameter | Description |
query (optional) | See Query Options |
opts (optional) | See Fetch Options |
Example: Load first 10 submissions, sort by descending created date
Example 2: Load first 20 submissions where the form field age is greater than 18, and sort by modified.
formio.loadActions([query], [opts])
formio.loadActions([query], [opts])
Loads the Actions for a given form. This implements the List Actions API
Parameter | Description |
query (optional) | See Query Options |
opts (optional) | See Fetch Options |
Examples will be very similar to the loadSubmissions API, but will query against the action json objects instead.
formio.availableActions()
formio.availableActions()
Returns a list of available actions that can be added to this form. Implements the Available Actions API.
formio.actionInfo(name)
formio.actionInfo(name)
Returns the action information for a specific action including the settings form. This implements the Action Info API
Parameter | Description |
name | The name of the action you would like to retrieve information on. |
Submission API Scope
The following API's are available when the Form.io SDK is instantiated with the submission scope like the following illustrates
formio.loadSubmission([query], [opts])
formio.loadSubmission([query], [opts])
Loads a submission for a given form.
Parameter | Description |
query (optional) | See Query Options |
opts (optional) | See Fetch Options |
Example: Load the submission
formio.saveSubmission(submission, [opts])
formio.saveSubmission(submission, [opts])
Creates or Updates a submission depending on if an "_id" property is provided within the submission json.
Parameter | Description |
submission | The JSON of the submission to save or update. If an "_id" is provided as a property of the submission json, then an update operation is performed, otherwise, it will create a new submission. |
opts (optional) | See Fetch Options |
Example: Create a new submission
Example: Update an existing submission
formio.deleteSubmission([opts])
formio.deleteSubmission([opts])
Deletes a submission
Property | Description |
opts (optional) | See Fetch Options |
formio.getDownloadUrl([form])
formio.getDownloadUrl([form])
Retrieves a PDF download url for a specific form.
Parameter | Description |
form | The form JSON to retrieve a download url from. If none is provided, then it will use the form that is in scope. |
formio.uploadFile(storage, file, fileName, dir, progressCallback, url, options, fileKey, groupPermissions, groupId, uploadStartCallback, abortCallback)
formio.uploadFile(storage, file, fileName, dir, progressCallback, url, options, fileKey, groupPermissions, groupId, uploadStartCallback, abortCallback)
Uploads a file to the provided storage system. See File Component for specific usage and implementation details.
formio.downloadFile(file, [options])
formio.downloadFile(file, [options])
Downloads a file from the provided storage system. See File Component for specific usage and implementation details.
formio.deleteFile(file, [options])
formio.deleteFile(file, [options])
Deletes a file from the provided storage system. See File Component for specific usage and implementation details
Action API Scope
The following API's are available when the Form.io SDK is instantiated with the action scope like the following illustrates
formio.loadAction([query], [opts])
formio.loadAction([query], [opts])
Loads an action for a given form.
Parameter | Description |
query (optional) | See Query Options |
opts (optional) | See Fetch Options |
Example: Load the action
formio.saveAction(action, [opts])
formio.saveAction(action, [opts])
Creates or Updates an action depending on if an "_id" property is provided within the action json.
Parameter | Description |
action | The JSON of the action to save or update. If an "_id" is provided as a property of the action json, then an update operation is performed, otherwise, it will create a new action. |
opts (optional) | See Fetch Options |
Example: Create a new action
Example: Update an existing submission
formio.deleteAction([opts])
formio.deleteAction([opts])
Deletes an action
Property | Description |
opts (optional) | See Fetch Options |
Role API Scope
The following API's are available when the Form.io SDK is instantiated with the role scope like the following illustrates
formio.loadRole([opts])
formio.loadRole([opts])
Loads a role json.
Parameter | Description |
opts (optional) | See Fetch Options |
Example: Load the role
formio.saveRole(role, [opts])
formio.saveRole(role, [opts])
Creates or Updates a role depending on if an "_id" property is provided within the role json.
Parameter | Description |
role | The JSON of the role to save or update. If an "_id" is provided as a property of the role json, then an update operation is performed, otherwise, it will create a new role. |
opts (optional) | See Fetch Options |
Example: Create a new role
Example: Update an existing role
formio.deleteRole([opts])
formio.deleteRole([opts])
Deletes a role
Property | Description |
opts (optional) | See Fetch Options |
Utility Methods
formio.isObjectId(id)
formio.isObjectId(id)
Determines if the provided "id" is a valid MongoDB ObjectId
formio.userPermissions([user], [form], [submission])
formio.userPermissions([user], [form], [submission])
Fetches an object that describes the users permissions as it pertains to the provided user, form, and submission. If any of these are not provided, then the current object in context is used.
formio.canSubmit()
formio.canSubmit()
Returns a promise if the user can submit the form in scope.
Fetch Plugin API
Formio.js can register plugins that can hook into request calls in several ways. Every fetch plugin is defined using the following JSON structure.
Formio.registerPlugin(plugin, [name])
Formio.registerPlugin(plugin, [name])
Registers a fetch plugin with the Form.io SDK.
Parameter | Description |
plugin | An instance of the Fetch plugin as described above. |
name (optional) | The name of this plugin so that it can be retrieved easily later |
Formio.getPlugin(name)
Formio.getPlugin(name)
Returns the plugin registered with the given name.
Formio.deregisterPlugin(plugin)
Formio.deregisterPlugin(plugin)
Deregisters a plugin with Form.io SDK. It will call the deregister
function on the plugin before deregistering. The plugin
argument can be the instance of the plugin or the optional name given when registered. Returns true if the plugin was successfully deregistered, false if the plugin does not exist.
Plugin hooks
Plugins can provide hooks that are invoked at different points in the library. To use a particular hook below, add a function to your plugin with the same name as the hook.
The following are the currently available hooks.
preRequest(requestArgs)
preRequest(requestArgs)
Called before a request. If you return a promise, Formio.js will wait for it to resolve before starting the request.
requestArgs
is an object that contains the following properties:
formio
: The Formio instance calling the request.type
: The type of resource being requested (ex: form, forms, submission).url
: The url being requested.method
: The HTTP request method.data
: The HTTP request body, if any.opts
: Any opts given to the request
request(requestArgs)
request(requestArgs)
Called before a request, and gives plugins a chance fulfill the request before it is sent. If you return a non-null, non-undefined value (or a promise that resolves to one), that will be used as the results of the request instead of making the default network request.
Only the first highest priority that returns a value will replace the contents. Your plugin's hook will not be called if a higher priority plugin returns a value.
requestArgs
is an object that contains the following properties:
formio
: The Formio instance calling the request.type
: The type of resource being requested (ex: form, forms, submission).url
: The url being requested.method
: The HTTP request method.data
: The HTTP request body, if any.opts
: Any opts given to the request
wrapRequestPromise(promise, requestArgs)
wrapRequestPromise(promise, requestArgs)
Called when a request is made and gives plugins access to the promise that is returned when a user makes a request. The promise that is returned from this hook will be returned to the user. You may wrap the original promise or extend the promise chain with this hook. (You must return a promise that uses the original promise, or the promise returned to users will not resolve as expected).
promise
is the promise of the request.
requestArgs
is an object that contains the following properties:
formio
: The Formio instance calling the request.type
: The type of resource being requested (ex: form, forms, submission).url
: The url being requested.method
: The HTTP request method.data
: The HTTP request body, if any.opts
: Any opts given to the request
preStaticRequest(requestArgs)
preStaticRequest(requestArgs)
Same as preRequest
hook but used for requests that use the global Formio object instead of a Formio instance. This includes functions like Formio.loadProjects()
, Formio.availableActions()
, Formio.currentUser()
.
requestArgs
is an object that contains the following properties:
url
: The url being requested.method
: The HTTP request method.data
: The HTTP request body, if any.
staticRequest(requestArgs)
staticRequest(requestArgs)
Same as request
hook but used for requests that use the global Formio object instead of a Formio instance. This includes functions like Formio.loadProjects()
, Formio.availableActions()
, Formio.currentUser()
.
requestArgs
is an object that contains the following properties:
url
: The url being requested.method
: The HTTP request method.data
: The HTTP request body, if any.
wrapStaticRequestPromise(promise, requestArgs)
wrapStaticRequestPromise(promise, requestArgs)
Same as wrapRequestPromise
hook but used for requests that use the global Formio object instead of a Formio instance. This includes functions like Formio.loadProjects()
, Formio.availableActions()
, Formio.currentUser()
.
promise
is the promise of the request.
requestArgs
is an object that contains the following properties:
url
: The url being requested.method
: The HTTP request method.data
: The HTTP request body, if any.
Example Plugin
This example plugin will delay all requests by 5 seconds
Query Options (query)
Many of the GET api calls made in this SDK include a variable called query. This is a variable that allows you to pass along query parameters to the URL's that will be used as the API endpoints. The following are properties that can be utilized within the query parameter.
Property | Description |
params | An object key-value pair that will be added to the URL as query parameters for the API call. Example: Load all forms, but filter them by resources and sort them by created descending.
The following will produce the following API url.
|
Fetch Options (opts)
All of the API calls made within this SDK contain a parameter that we will call opts. This is a variable that allows you to pass special options to the fetch methods for the API call being made. The following are properties that can be utilized within the opts parameter.
Property | Description |
header | An instance of the Headers class to define the headers of the request |
headers | A JavaScript object key-value map of the headers you would like to introduce. Example:
|
formio | A custom instance of the Form.io SDK to use for this request. |
ignoreCache | Boolean (true) to tell the request to ignore any memory cache of the request. This is useful if you make a request that changes something and then wish to GET additional data without using the cached response. Example:
|
noToken | Boolean (true) to tell the API call to not include the Form.io JWT token along with the request. |
namespace | The namespace to use as a prefix of all variables being saved into localStorage for this request. For example, setting this to "test" will save the JWT token into the "testToken" variable instead of the default "formioToken" |
Last updated