Skip to main content
Announcements
See what Drew Clarke has to say about the Qlik Talend Cloud launch! READ THE BLOG
cancel
Showing results for 
Search instead for 
Did you mean: 
olaoyesunday1
Contributor III
Contributor III

Pulling Data from Qlik Cloud through python on window machine

Hello folks,

I am trying to read data from Qlik Cloud into my Python script on my Windows laptop, but I'm encountering errors:

 

import requests
import pandas as pd
import matplotlib.pyplot as plt
import base64
import json
qlik_base_url = "https://mytenant.qlikcloud.com/"
qlik_app_id = "f5555629-bb12-4983-854b-1ed7c9682f55"
qlik_table_object_id = "ZgGPbV"
qlik_api_token = "api_key" #this api key is correct

qlik_data_url = f"{qlik_base_url}/api/v1/apps/{qlik_app_id}/tables/{qlik_table_object_id}/data" 
headers = { "Authorization": "Bearer " + qlik_api_token } 
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

 

but the output is 

Failed to fetch data. Status code: 401

 please, can anyone help me to resolve this, I am using correct api_key, my url, appId and object Id are all correct 

Labels (6)
2 Replies
jprdonnelly
Employee
Employee

@olaoyesunday1 ,

Please investigate the following links:

The Reporting API off-loads the export/PDF generation workload from the Engine in Qlik Cloud. You will be able to achieve the same outcome, it will just require a different approach.

Cheers!

- @jprdonnelly
olaoyesunday1
Contributor III
Contributor III
Author

@jprdonnelly  Thanks,

I converted the C# example to python but it was giving the following errors:

NameError                                 Traceback (most recent call last)
Cell In[8], line 61
     58     return json.dumps(body)
     60 if __name__ == "__main__":
---> 61     main()

Cell In[8], line 14, in main()
     11 output_file = "output.xlsx"
     13 # Initialize RestClient
---> 14 client = RestClient(url)
     15 client.as_api_key_via_qcs(api_key)
     17 # Create request body

NameError: name 'RestClient' is not defined

here is my code:

import requests
import json
import time
# import RestClients

def main():
    url = "https://tenant.eu.qlikcloud.com"
    api_key = "api key"
    object_id = "ZgGPbV"
    output_file = "output.xlsx"

    # Initialize RestClient
    client = RestClient(url)
    client.as_api_key_via_qcs(api_key)

    # Create request body
    request_body = create_request_body(app_id, object_id)

    # Post request to initiate report generation
    http_rsp = client.post_http_async("/api/v1/reports", request_body)
    http_result = http_rsp.result()
    status_location = http_result.headers["Location"]

    print("Report generation requested. Awaiting process to complete...")
    data_location = await_export_completion(client, status_location)

    print("Report generation completed. Downloading exported file...")
data_location_uri = urljoin(url, data_location)
    bytes_data = client.get_bytes(data_location_uri)

    with open(output_file, "wb") as f:
        f.write(bytes_data)

    print(f"Wrote {len(bytes_data)} bytes to file: {output_file}")

def await_export_completion(client, status_location):
    rsp = client.get_json(status_location)
    while rsp["status"] != "done":
        print("    Current status:", rsp["status"])
        time.sleep(1)
        rsp = client.get_json(status_location)
    print("    Current status:", rsp["status"])
    return rsp["results"][0]["location"]

def create_request_body(app_id, object_id):
    body = {
        "type": "sense-data-1.0",
        "output": {
            "outputId": "Chart_excel",
            "type": "xlsx"
        },
        "senseDataTemplate": {
            "appId": app_id,
            "id": object_id
        }
    }
   return json.dumps(body)

if __name__ == "__main__":
    main()