Forum Discussion

Ashok42470's avatar
Ashok42470
Copper Contributor
Mar 07, 2025

Getting empty response while running a kql query using rest api

Hello All,

 

Trying to run a KQL query using power via rest API by passing azure Entra app id and secret key.  But we are getting empty response. Log analytics reader role is assigned on LA workspace and able to retrieve access token. When we try to run KQL query manually, we are seeing result. Below is sample snippet that i used, Not sure what is wrong with it? Any help would be highly appreciated.

 

$tenantId = <Tenant id>
$clientId = <azure entra application app id>
$clientSecret = < app secret key>

# Log Analytics Workspace details
$workspaceId = <workspace ID>


# Acquire a token
$body = @{
    client_id = $clientId
    scope = "https://api.loganalytics.io/.default"
    client_secret = $clientSecret
    grant_type = "client_credentials"
}

$query = "AppRequests | limit 10"

$uri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
$response = Invoke-RestMethod -Uri $uri -Method Post -ContentType "application/x-www-form-urlencoded" -Body $body

$accessToken = $response.access_token 

# Define the Log Analytics REST API endpoint
$baseUri = "https://api.loganalytics.io/v1/workspaces/$workspaceId/query"

# Set headers for the query
$headers = @{
    Authorization = "Bearer $accessToken"
    "Content-Type" = "application/json"
}

# Prepare the request body
$requestbody = @{
    query = $query
} | ConvertTo-Json

# Send the request
$response = Invoke-RestMethod -Uri $baseUri -Method Post -Headers $headers -Body $requestbody -Debug 

# Display the results
$response

  • May consider to modify your script slightly to capture and inspect the response for more insights:

     

    try {
        $response = Invoke-RestMethod -Uri $baseUri -Method Post -Headers $headers -Body $requestbody -Debug
        Write-Host "Response:" -ForegroundColor Green
        $response
    } catch {
        Write-Host "Error:" -ForegroundColor Red
        $_.Exception.Message
        $_.Exception.Response.Content | ConvertFrom-Json
    }
    

     

Resources