8 min read

With mashups or web apps, the Qlik Engine sits outside of your project and is not accessible and loaded by default. The first step before doing anything else is to create a connection with the Qlik Engine, after which you can continue to open a session and perform further actions on that app, such as:

  • Opening a document/app
  • Making selections
  • Retrieving visualizations and apps

For using the Qlik Engine API, open a WebSocket to the engine. There may be a difference in the way you do this, depending on whether you are working with Qlik Sense Enterprise or Qlik Sense Desktop. In this article, we will elaborate on how you can achieve a connection to the Qlik engine and the benefits of doing so.

The following excerpt has been taken from the book Mastering Qlik Sense, authored by Martin Mahler and Juan Ignacio Vitantonio.

Creating a connection

To create a connection using WebSockets, you first need to establish a new web socket communication line. To open a WebSocket to the engine, use one of the following URIs:

Qlik Sense Enterprise Qlik Sense Desktop
wss://server.domain.com:4747/app/ or

wss://server.domain.com[/virtual proxy]/app/

ws://localhost:4848/app

Creating a Connection using WebSockets

In the case of Qlik Sense Desktop, all you need to do is define a WebSocket variable, including its connection string in the following way:

var ws = new WebSocket("ws://localhost:4848/app/");

Once the connection is opened and checking for ws.open(), you can call additional methods to the engine using ws.send().

This example will retrieve the number of available documents in my Qlik Sense Desktop environment, and append them to an HTML list:

<html>
<body>
<ul id='docList'>
</ul>
</body>
</html>
<script>
var ws = new WebSocket("ws://localhost:4848/app/");
var request = {
     "handle": -1,
     "method": "GetDocList",
     "params": {},
     "outKey": -1,
     "id": 2
}
ws.onopen = function(event){
     ws.send(JSON.stringify(request));
     // Receive the response
     ws.onmessage = function (event) {
         var response = JSON.parse(event.data);
         if(response.method != ' OnConnected'){
             var docList = response.result.qDocList;
             var list = '';
             docList.forEach(function(doc){
                 list += '<li>'+doc.qDocName+'</li>';
             })
         document.getElementById('docList').innerHTML = list;
         }
    }
}
</script>

The preceding example will produce the following output on your browser if you have Qlik Sense Desktop running in the background:

Qlik sense desktop background
All Engine methods and calls can be tested in a user-friendly way by exploring the Qlik Engine in the Dev Hub.
A single WebSocket connection can be associated with only one engine session (consisting of the app context, plus the user). If you need to work with multiple apps, you must open a separate WebSocket for each one.

If you wish to create a WebSocket connection directly to an app, you can extend the configuration URL to include the application name, or in the case of the Qlik Sense Enterprise, the GUID. You can then use the method from the app class and any other classes as you continue to work with objects within the app.

var ws = new WebSocket("ws://localhost:4848/app/MasteringQlikSense.qvf");

Creating  Connection to the Qlik Server Engine

Connecting to the engine on a Qlik Sense environment is a little bit different as you will need to take care of authentication first. Authentication is handled in different ways, depending on how you have set up your server configuration, with the most common ones being:

  • Ticketing
  • Certificates
  • Header authentication

Authentication also depends on where the code that is interacting with the Qlik Engine is running.

If your code is running on a trusted computer, authentication can be performed in several ways, depending on how your installation is configured and where the code is running:

  • If you are running the code from a trusted computer, you can use certificates, which first need to be exported via the QMC
  • If the code is running on a web browser, or certificates are not available, then you must authenticate via the virtual proxy of the server

Creating a connection using certificates

Certificates can be considered as a seal of trust, which allows you to communicate with the Qlik Engine directly with full permission. As such, only backend solutions ever have access to certificates, and you should guard how you distribute them carefully. To connect using certificates, you first need to export them via the QMC, which is a relatively easy thing to do:

connection using certificates

Once they are exported, you need to copy them to the folder where your project is located using the following code:

<html>
<body>
<h1>Mastering QS</h1>
</body>
<script>
var certPath =  path.join('C:', 'ProgramData', 'Qlik', 'Sense', 'Repository', 'Exported Certificates', '.Local Certificates');

var certificates = {
        cert: fs.readFileSync(path.resolve(certPath, 'client.pem')),
        key: fs.readFileSync(path.resolve(certPath, 'client_key.pem')),
        root: fs.readFileSync(path.resolve(certPath, 'root.pem'))
        };

// Open a WebSocket using the engine port (rather than going through the proxy)
var ws = new WebSocket('wss://server.domain.com:4747/app/', {
        ca: certificates.root,
        cert: certificates.cert,
        key: certificates.key,
        headers: {
                        'X-Qlik-User':  'UserDirectory=internal; UserId=sa_engine'
        }
        });
       
ws.onopen = function (event) {
 // Call your methods
}
</script>

Creating a connection using the Mashup API

Now, while connecting to the engine is a fundamental step to start interacting with Qlik, it’s very low-level, connecting via WebSockets. For advanced use cases, the Mashup API is one way to help you get up to speed with a more developer-friendly abstraction layer.

The Mashup API utilizes the qlik interface as an external interface to Qlik Sense, used for mashups and for including Qlik Sense objects in external web pages.

To load the qlik module, you first need to ensure RequireJS is available in your main project file. You will then have to specify the URL of your Qlik Sense environment, as well as the prefix of the virtual proxy, if there is one:

<html>
<body>
<h1>Mastering QS</h1>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.5/require.min.js">
<script>
//Prefix is used for when a virtual proxy is used with the browser.
var prefix = window.location.pathname.substr( 0, window.location.pathname.toLowerCase().lastIndexOf( "/extensions" ) + 1 );
//Config for retrieving the qlik.js module from the Qlik Sense Server
var config = {
host: window.location.hostname,
prefix: prefix,
port: window.location.port,
isSecure: window.location.protocol === "https:"
};

require.config({
baseUrl: (config.isSecure ? "https://" : "http://" ) + config.host + (config.port ? ":" + config.port : "" ) + config.prefix + "resources"
});

require(["js/qlik"], function (qlik) {
qlik.setOnError( function (error) {
console.log(error);
});
//Open an App
var app = qlik.openApp('MasteringQlikSense.qvf', config);
</script>

Once you have created the connection to an app, you can start leveraging the full API by conveniently creating HyperCubes, connecting to fields, passing selections, retrieving objects, and much more.

The Mashup API is intended for browser-based projects where authentication is handled in the same way as if you were going to open Qlik Sense. If you wish to use the Mashup API, or some parts of it, with a backend solution, you need to take care of authentication first.

Creating a connection using enigma.js

Enigma is Qlik’s open-source promise wrapper for the engine. You can use enigma directly when you’re in the Mashup API, or you can load it as a separate module.

When you are writing code from within the Mashup API, you can retrieve the correct schema directly from the list of available modules which are loaded together with qlik.js via 'autogenerated/qix/engine-api'.

 

The following example will connect to a Demo App using enigma.js:

define(function () {
  return function () {
    require(['qlik','enigma','autogenerated/qix/engine-api'], function (qlik, enigma, schema) {
//The base config with all details filled in 
var config = { 
     schema: schema,
     appId: "My Demo App.qvf",
     session:{
         host:"localhost",
         port: 4848,
         prefix: "",
         unsecure: true,
     },
}
//Now that we have a config, use that to connect to the //QIX service.
enigma.getService("qix" , config).then(function(qlik){
     qlik.global.openApp(config.appId)
    //Open App
      qlik.global.openApp(config.appId).then(function(app){
        //Create SessionObject for FieldList
        app.createSessionObject( {
          qFieldListDef: {
              qShowSystem: false,
              qShowHidden: false,
              qShowSrcTables: true,
              qShowSemantic: true,
              qShowDerivedFields: true
          }, qInfo: {
              qId: "FieldList",
              qType: "FieldList"
          }
      } ).then( function(list) {
          return list.getLayout();
      } ).then( function(listLayout) {
          return listLayout.qFieldList.qItems;
      } ).then( function(fieldItems) {
         console.log(fieldItems)
      } );
      })
}
})}})

It’s essential to also load the correct schema whenever you load enigma.js. The schema is a collection of the available API methods that can be utilized in each version of Qlik Sense. This means your schema needs to be in sync with your QS version.

Thus, we see it is fairly easy to create a stable connection with the Qlik Engine API.

If you liked the above excerpt, make sure you check out the book Mastering Qlik Sense to learn more tips and tricks on working with different kinds of data using Qlik Sense and extract useful business insights.

Read Next:

How Qlik Sense is driving self-service Business Intelligence

Overview of a Qlik Sense® Application’s Life Cycle

What we learned from Qlik Qonnections 2018

Data Science Enthusiast. A massive science fiction and Manchester United fan. Loves to read, write and listen to music.

LEAVE A REPLY

Please enter your comment!
Please enter your name here