Search code examples
azureazure-api-managementazure-log-analyticsazure-api-apps

How to run log analytics query using azure api?


I have been trying to run a log analytics query using Azure API but its returns some error { "error": { "message": "Valid authentication was not provided", "code": "AuthorizationRequiredError", "correlationId": "27301475d-cc29-4288-ae61-29e77d6d05cb" } }

this was the request I have been trying

https://api.loganalytics.io/v1/workspaces/34567824-3432rewfsdewt435-3424jhh-dsa-/query?query=search in (ContainerLog) "search_data"| where TimeGenerated > datetime("2020-09-03")| project LogEntry & Authorization=Bearer 0000000000000000000000000000

if you guys know anything please help me Thank you


Solution

  • When we use Azure Log Analytics REST API to do a query, we need to user Authorization=Bearer {token} as request Headers. For more details, please refer to here. enter image description here

    For example

    1. Register Azure AD application

    2. Configure API permissions for the AD application enter image description here

    3. Give the AAD Application access to our Log Analytics Workspace. Please assign Log Analytics Reader role to the AD application

    4. Get access token

    POST /<your tenant id>/oauth2/token HTTP/1.1
    Host: login.microsoftonline.com
    Content-Type: application/x-www-form-urlencoded
    
    grant_type =client_credentials
    &client_id=<>
    &client_secret=<>
    &resource=https://westus2.api.loganalytics.io
    
    1. Call the api

    a. POST method

    POST https://api.loganalytics.io/v1/workspaces/{workspaceId}/query
    Authorization: Bearer {access_token}
    Content-Type: application/json
    
    {
        "query": ""
    }
    
    

    enter image description here

    b. Get method

    GET https://api.loganalytics.io/v1/workspaces/{workspaceId}/query?query={query}
    
    Authorization: Bearer {access_token}
    

    enter image description here