Log Analytics Workspace - Python pull data from API

Menta, SivaKumar 15 Reputation points
2023-09-11T05:02:47.6666667+00:00

I need your help with Log Analytics workspace related problem.

 I’m trying to extract data from Log Analytics API for ML alert using Python but facing with permission related error while extracting the data. It would be of great support if you could guide me through this problem asap today.

 

FYI…Implemented the steps suggested in the documentation page (Link)

 Python script:

# Obtain an access token using client credentials
token_url = f'https://login.microsoftonline.com/{tenant_id}/oauth2/token'
token_data = {
    'grant_type': 'client_credentials',
    'client_id': client_id,
    'client_secret': client_secret,
    'resource': resource
}
token_response = requests.post(token_url, data=token_data)
access_token = token_response.json().get('access_token')

# Query parameters
# API endpoint for querying Log Analytics data

query = ""
query_url = schema['data']['alertContext']['condition']['allOf'][0]['linkToFilteredSearchResultsAPI']
    
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}

query_data = {    'query': query    }

# Use Certifi's CA certificate bundle
cafile = certifi.where()
response = requests.get(query_url, headers=headers, data=json.dumps(query_data), verify=cafile)

Error messages:

 User's image

User's image

Regards,

Siva Kumar Menta

Azure Monitor
Azure Monitor
An Azure service that is used to collect, analyze, and act on telemetry data from Azure and on-premises environments.
3,645 questions
{count} votes

1 answer

Sort by: Most helpful
  1. AnuragSingh-MSFT 21,546 Reputation points Moderator
    2023-09-15T07:15:43.72+00:00

    Menta, SivaKumar, thank you for posting this question and apologies for the delayed response.

    Based on the error reported "Provided credentials have insufficient access...", it seems that the step below was missed/not followed completely for the app registered in Azure AD (of which the client and secret is being used to get token): Register an App to request authorization tokens and work with Log Analytics APIs.

    I would suggest running the first half of the python script shared to get the access token and then use tools like VS Code with REST Client OR Postman to make the request directly and get the response back. This would help validate the token and its authorization to use the API.

    The following additional links should help you in this regard:

    Hope this helps.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.