Search code examples
pythonpandaspython-requestshttp-status-code-401qliksense

Fix failed connection to Qlik with status code 401


I am trying to generate detailed python scripts to read Json data from a Qlik cloud bar chart, output it as a pdf file on my laptop but I keep getting an error message 401. i,e Failed to fetch data:

Failed to fetch data. Status code: 401 # output from the try loop in the code below

# Then full error traceback:
Traceback (most recent call last):
  File "c:\Users\Sunday\Documents\ClikModules\appv3ntpj.py", line 41, in <module>
    plt.bar(df['Customer'], df['Sum(Sales)'])
            ~~^^^^^^^^^^^^
  File "C:\Users\Sunday\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\frame.py", line 3893, in __getitem__
    indexer = self.columns.get_loc(key)
              ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Sunday\AppData\Local\Programs\Python\Python312\Lib\site-packages\pandas\core\indexes\range.py", line 418, in get_loc
    raise KeyError(key)
KeyError: 'Customer'

The code below cannot connect, thus the try loop isses an empty dataframe, after which the attempt to plot it, understandably, raises the error described in the above traceback.

import requests
import pandas as pd
import matplotlib.pyplot as plt
import base64

# Qlik Sense Configuration
qlik_base_url = "https://ioco2.eu.qlikcloud.com/"
qlik_app_id = "d0c200c8-b3bb-4157-81b7-4d18d44856a3"
qlik_table_object_id = "tNfNKkC"

# Authentication credentials (replace with your actual credentials)
qlik_username = "my username"
qlik_password = "password"

# Fetch data from Qlik Sense with authentication headers
qlik_data_url = f"{qlik_base_url}/api/v1/apps/{qlik_app_id}/tables/{qlik_table_object_id}/data"
headers = {
    "Authorization": "Basic " + base64.b64encode(f"{qlik_username}:{qlik_password}".encode()).decode()
}
response = requests.get(qlik_data_url, headers=headers)

# Check for successful response status
if response.status_code == 200:
    try:
        table_data = response.json()
    except requests.exceptions.JSONDecodeError as e:
        print(f"Error decoding JSON: {e}")
        table_data = None
else:
    print(f"Failed to fetch data. Status code: {response.status_code}")
    table_data = None

# Continue with the rest of the script...

# Convert Qlik table data to a Pandas DataFrame
df = pd.DataFrame(table_data) # So this will be empty

# Data processing or analysis (replace this with your specific requirements)
# For this example, let's just plot the data and save it as a PDF
plt.figure(figsize=(10, 6))
plt.bar(df['Customer'], df['Sum(Sales)']) # raises the error
plt.xlabel('Customer')
plt.ylabel('Sum(Sales)')
plt.title('Top Customers by Sales in Qlik Sense')

Please help me fix this status code 401.


Solution

  • I have gotten the answer, here is the solution:

    import pytoqlik
    import seaborn  # Seaborn provides us with some sample datasets 
    import pandas as pd   # We will need pandas to manipulate the extracted DataFrame
    

    Generate the api-key from the Qlik console and do the following:

    key='eyJhbGciOiJFUzM4NCIsImtpZCI6IjczZWUwNDgzLTc1NGYtNDc3Yy'
    url='https://pytoqlik-bestlib.us.qlikcloud.com/'
    ID='5078a285-39f8-4bd1-8b1b-351d6cef77ea'
    
    p2q = pytoqlik.Pytoqlik(api_key=key, tenant=url, appId=appId)
    

    with the above you can read any object from the Qlik like the one below:

    p2q.toPy('qCZbkW')