Using the Workflow REST API in JavaScript

This topic provides some samples that demonstrate how to interact with the Workflow REST API through JavaScript.

In the code samples below, you will need to replace values in square brackets with the appropriate values for your K2 environment. For example, the value [K2RESTSERVICEBASEURL] refers to the location of the K2 Site where the service is hosted. You can determine the REST service's URL for you environment through the K2 Management Site by navigating to IntegrationAPIsWorkflow REST, the URL will be displayed in the Base URL property. The URL may look something like this, of course the value would be different for your environment: https://k2serverprod:4444/api/workflow/v1
Copy

Retrieve a list of Workflows you have rights to access

/*
 * Returns a list of Workflows either owned or startable for the user credentials supplied.
 */
$(document).on("click", "#listwfs", function () {
    $.ajax({
        type: 'GET',
        // Your URL is different to the one below. Enter your server address in the placeholder.
        // Use the Swagger descriptor from the Workflow REST API Configuration page on the K2 Management site
        // to get your base URL for the url: line.
        // The optional 'type' parameter returns either 'startable' or 'owned' workflows.
        // If no 'type' parameter is set, 'startable' workflows are returned. The URL with 'type' set:
        // [K2RESTSERVICEBASEURL]/workflows?type=Owned
        url: '[K2RESTSERVICEBASEURL]/workflows/',
        dataType: 'json',
        // As CORS is used, this must be set to true
        crossDomain: false,
        // Basic authentication is set in the header, enter your user name and password in the placeholders.
        // The xhr (XMLHttpRequest) function below sends authorization details to the server.
        //
        // This line creates a hash of the user name and password:
        // window.btoa(unescape(encodeURIComponent("[USERNAME]" + ':' + "[PASSWORD]")))
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Authorization', 'Basic ' + window.btoa(unescape(encodeURIComponent("[USERNAME]" + ':' + "[PASSWORD]"))));
            xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
        },
        // On success, we write a 'success' message to the console and stringify the returned JSON to display, 
        // for example, in the <div id="wfs"><div> tag on a web page 
        success: function (json_data) {
            console.log('success');
            $("#wfs").html(JSON.stringify(json_data));
        },
        // In case of error, show an alert
        error: function () {
            alert('Failed!');
        },
    });
});
Copy

Return the metadata definition for a Workflow

/*
 * Returns a workflow metadata definition for a particular Workflow ID 
 */
$(document).on("click", "#listwfid", function () {
    $.ajax({
        type: 'GET',
        // your URL would be different. Enter your server address in the placeholder
        // use the Swagger descriptor from the Workflow REST API Configuration page on the K2 Management site
        // to get your base URL for the url: line 
        // Replace the Workflow ID number [WFID] placeholder with your Workflow ID.
        // You can get the ID by using the "Return a list of Workflows" snippet or with the
        // Swagger descriptor from the Workflow REST API Configuration page on the K2 Management site.
        url: '[K2RESTSERVICEBASEURL]/workflows/[WFID]',
        dataType: 'json',
        // As CORS is used, this must be set to true
        crossDomain: false,
        // Basic authentication is set in the header, enter your user name and password in the placeholders
        // The xhr (XMLHttpRequest) function below sends authorization details to the server
        //
        // The following line creates a hash of the user name and password:
        // window.btoa(unescape(encodeURIComponent("[USERNAME]" + ':' + "[PASSWORD]")))
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Authorization', 'Basic ' + window.btoa(unescape(encodeURIComponent("[USERNAME]" + ':' + "[PASSWORD]"))));
            xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
        },
        // On success, we write a 'success' message to the console and stringify the returned JSON to display 
        // in the <div id="wfid"><div> tag on a web page for example
        success: function (json_data) {
            console.log('success');
            $("#wfid").html(JSON.stringify(json_data));
        },
        // In case of error, show an alert
        error: function () {
            alert('Failed!');
        },
    });
}); 
Copy

Create and start an instance of a Workflow

/*
 * Start a Workflow instance. 
 * Send values for folio and datafields etc. in JSON notation.
 * The Workflow REST API accepts string data in JSON notation.
 */
$(document).on("click", "#startwf", function () {
    // Create your JSON data object that is stringified as part of your POST.
    var data = {
        "folio": "Tuesday Folio",
        "expectedDuration": 26000,
        "priority": 1,
        "dataFields": {
            "TextDataField": "This is Tuesday data",
            "DateDataField": Date.now().toString
        }
    }
    $.ajax({
        type: 'POST',
        // your URL would be different. Enter your server address in the placeholder
        // use the Swagger descriptor from the Workflow REST API Configuration page on the K2 Management site
        // to get your base URL for the url: line 
        // Replace the Workflow ID number [WFID] placeholder with your Workflow ID.
        // You can get the ID by using the "Return a list of Workflows" snippet or with the
        // Swagger descriptor from the Workflow REST API Configuration page on the K2 Management site.
        url: '[K2RESTSERVICEBASEURL]/workflows/[WFID]',
        // The data to POST is declared as a variable (var data) and stringified here when sent to the server.
        data: JSON.stringify(data),
        processData: false,
        dataType: 'json',
        // As CORS is used, this must be set to true
        crossDomain: true,
        // Basic authentication is set in the header, enter your user name and password in the placeholders
        // The xhr (XMLHttpRequest) function below sends authorization details to the server
        //
        // The following line creates a hash of the user name and password:
        // window.btoa(unescape(encodeURIComponent("[USERNAME]" + ':' + "[PASSWORD]")))
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Authorization', 'Basic ' + window.btoa(unescape(encodeURIComponent("[USERNAME]" + ':' + "[PASSWORD]"))));
            xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
        },
        // On success, we write a 'success' message to the console and stringify the returned JSON to display 
        // in the <div id="wfid"><div> tag on a web page for example
        success: function (json_data) {
            console.log('success');
            $("#swf").html("Instance started and new folio sent. Data sent: " + JSON.stringify(data));
        },
        // In case of error, show an alert
        error: function (error) {
            alert('Failed! ' + error);
            console.log(request.responseText);
        }
    });
});
Copy

Get a list of Tasks for the current user

/*
 * Get a list of tasks for the current user.
 */
$(document).on("click", "#GetWorklist", function () {
    $.ajax({
        type: 'GET',
        // Your URL is different to the one below. Enter your server address in the placeholder.
        // Use the Swagger descriptor from the Workflow REST API Configuration page on the K2 Management site
        // to get your base URL for the url: line.
        // The optional 'type' parameter returns either 'startable' or 'owned' workflows.
        // If no 'type' parameter is set, 'startable' workflows are returned. The URL with 'type' set:
        // [K2RESTSERVICEBASEURL]/workflows?type=Owned
        url: '[K2RESTSERVICEBASEURL]/tasks',
        dataType: 'json',
        // As CORS is used, this must be set to true
        crossDomain: false,
        // Basic authentication is set in the header, enter your user name and password in the placeholders.
        // The xhr (XMLHttpRequest) function below sends authorization details to the server.
        //
        // This line creates a hash of the user name and password:
        // window.btoa(unescape(encodeURIComponent("[USERNAME]" + ':' + "[PASSWORD]")))
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Authorization', 'Basic ' + window.btoa(unescape(encodeURIComponent("[USERNAME]" + ':' + "[PASSWORD]"))));
            xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
        },
        // On success, we write a 'success' message to the console and stringify the returned JSON to display, 
        // for example, in the <div id="wfs"><div> tag on a web page 
        success: function (json_data) {
            console.log('success');
            $("#tl").html(JSON.stringify(json_data));
        },
        // In case of error, show an alert
        error: function () {
            alert('Failed!');
        },
    });
});
Copy

Action a Task and update datafields

/*
 * Action a task and update datafields.
 */
$(document).on("click", "#update", function () {
    // Create your JSON data object that is stringified as part of your POST.
    var data = {
        "dataFields": {
            "TextDataField": "instance complete",
            "DateDataField": Date.now().toString
        }
    }
    $.ajax({
        type: 'POST',
        // your URL would be different. Enter your server address in the placeholder
        // use the Swagger descriptor from the Workflow REST API Configuration page on the K2 Management site
        // to get your base URL for the url: line 
        // Replace the instance ID placeholder [IID} with your Workflow's instance ID and the 
        // [ACTION] placeholder with your action.
        url: '[K2RESTSERVICEBASEURL]/tasks/[IID]/actions/[ACTION]',
        data: JSON.stringify(data),
        processData: false,
        dataType: 'application/json',
        // As CORS is used, this must be set to true
        crossDomain: true,
        // Basic authentication is set in the header, enter your user name and password in the placeholders
        // The xhr (XMLHttpRequest) function below sends authorization details to the server
        //
        // The following line creates a hash of the user name and password:
        // window.btoa(unescape(encodeURIComponent("[USERNAME]" + ':' + "[PASSWORD]")))
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Authorization', 'Basic ' + window.btoa(unescape(encodeURIComponent("[USERNAME]" + ':' + "[PASSWORD]"))));
            xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
        },
        // On success, we write a 'success' message to the console and stringify the returned JSON to display 
        // in the <div id="wfid"><div> tag on a web page for example
        success: function (json_data) {
            console.log('success');
            $("#upd").html("Instance started and new folio sent. Data sent: " + JSON.stringify(data));
        },
        // In case of error, show an alert
        error: function () {
            alert('Failed!');
        },
    });
});