Forum Discussion

Krishna1994's avatar
Krishna1994
Copper Contributor
Jun 20, 2024

Unable to retrieve query data using Log Analytics API

I have been trying to access Azure KQL data with the help of Log Analytics REST API, the connection is successful showing a 200 response but I am only getting the table headers and not getting any data in the table. Does anyone know how to resolve this?

 

Code snippet:

import requests

import urllib3

from azure.identity import DefaultAzureCredential

from datetime import datetime, timedelta, timezone

import certifi

import os

 

os.environ["REQUESTS_CA_BUNDLE"] = certifi.where()

verify_cert = certifi.where()

 

credential = DefaultAzureCredential()

 

# Set the start and end time for the query

end_time = datetime.now(timezone.utc)

start_time = end_time - timedelta(hours=6)

 

# Set the query string

query = '''

    KubePodInventory

    | take 5

'''

 

# Set the workspace ID

workspace_id = "XXXXXXXXXXXXXXXXXXXXXXXX"

 

# Set the API endpoint

api_endpoint = f"https://api.loganalytics.io/v1/workspaces/{workspace_id}/query"

 

# Set the request payload

payload = {

    "query": query,

    "timespan": f"{start_time.isoformat()}Z/{end_time.isoformat()}Z"

}

 

# Set the request headers

headers = {

    "Content-Type": "application/json"

}

 

# Disable SSL certificate verification

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

 

# Authenticate the request using the Azure credential

access_token = credential.get_token("https://api.loganalytics.io/.default").token

headers["Authorization"] = f"Bearer {access_token}"

 

# Send the POST request

response = requests.post(api_endpoint, json=payload, headers=headers, verify=False)

 

# Check the response status

if response.status_code == 200:

    data = response.json()

    tables = data.get('tables', [])

    if tables:

        table = tables[0]  # Assuming there is only one table returned

        columns = table.get('columns', [])

        rows = table.get('rows', [])

        if columns and rows:

            for row in rows:

                for i, column in enumerate(columns:(

                    column_name = column['name']

                    column_type = column['type']

                    row_value = row[i]

                    print(f"Column name: {column_name}, Data type: {column_type}, Value: {row_value}")

        else:

            print("Empty table or no data in table")

    else:

        print("No tables found in the response")

else:

    print(f"Request failed with status code: {response.status_code}")

    print(f"Error message: {response.text}")

 

1 Reply

  • Please check on below:

     

    • Permissions: Ensure that the credentials you're using have the necessary permissions to access the data in the Log Analytics workspace. You might need to verify the roles and permissions assigned to the service principal or user account.
    • Query Syntax: Double-check the KQL query syntax to ensure it's correct and that it should return data. You can test the query directly in the Log Analytics portal to see if it returns results there.
    • API Endpoint: Make sure the API endpoint and query parameters are correctly set up. Sometimes, appending the query string directly in the URL can help.
    • Data Availability: Verify that there is data available within the specified timespan. If there's no data, the query will return an empty table.
    • API Version: Ensure you're using the correct version of the Log Analytics API. Sometimes, updates or changes to the API might require adjustments in the code.

Resources