Qlik Sense SaaS API Connection using Python

In order to manage multiple tenants or complex Qlik Sense SaaS platforms soon you will find you want to automate a lot of your administrative tasks.

Taking the Qlik CLI once step further from single commands we can use a programing language (Python) to create multi step processes.

sudo apt install python3-pip
python -m pip install requests

For this example I’m going to use the ‘requests’ python module to request data from the Qlik api. The syntax is different from the CLI interface. Here we send though three main pieces of information:

qlik.api.urlyour tenant URL plus you location ending in “qlikcloud.com/api/v1/”
header authorizationyour long secrete api key, this can be found in your contexts.yml file
(optional) parameters

Qlik Python Hello World

#!/usr/bin/python

# Hello Qlik Cloud Python Program
import requests
import json

print ("Hello Qlik Cloud!");

apiurl ="[Your Details].qlikcloud.com/api/v1/"
headers = {"Authorization": "Authorization: Bearer [Long API key]"}

This is our basic bolier plate and can be run from the WSL terminal.

We send an API request using the python library requests we’ve just imported. The result comes back as text but by adding .json() at the end we can convert it (json is the second library we installed).

Firstly lets list our spaces within the tenant. For this we need to go to that API end point end point “spaces”.

...
result = requests.get(apiurl + "spaces",headers=headers).json()
print(json.dumps(result, indent=4, separators=(". ", " = ")))

We print the results to the console and use a bit of json formatting code to prettify the results.

If your result looks something like this then congratulations! You’ve created your first API call using Python!

We can also pass parameters though to limit our results. A full list can be found in the API documentation, https://qlik.dev/apis/rest/spaces/#%23%2Fentries%2Fv1%2Fspaces-get.

If we update the code and add some “params” in a dictionary format. Here we want to limit the results to just managed spaces:

...
#Sending params to the API request
payload={'type':'managed'}
result = requests.get(apiurl + "spaces",headers=headers,params=payload).json()

print(json.dumps(result, indent=4, separators=(". ", " = ")))

Working with your returned data

Now we have this information in our result variable we can loop through through the results and access the data keys with Python.

...
workable_data = result["data"]
print(workable_data) 

for item in workable_data: 
    print(item["id"], item["type"])

Happy Qliking!

Leave a comment