If you are in a squeeze to use Classic App Insights before its retirement in Feb 2023, I've just figured it out from digging bits of some old docs I've found in this other question and a mix of other sources like this one:
- REST API will have to do, because of the impending retirement
- Navigate to the 'API Access' blade for the classic app insights instance in Azure Portal
- Create an API key (The solution is short-lived and will be replaced upon migrating to workspace-based app insights anyway, so I didn't have to worry about the use of API keys ending in March 2026, though the Entra method will be the way to go in the newer solution that uses the JavaScript SDK.)
- Keep the API Key somewhere safe and reasonable
- Return to API Access blade and take note of the App ID
- Make a HTTP request (in your application code)
- URL: https://api.applicationinsights.io/v1/apps/<app-id-here>/query
- Include the API key as a HTTP header 'X-Api-Key'
- include the necessary KQL query as a parameter (?query=<your KQL here>)
- in my case it was the pageViews table that i needed, plus some massaging (?query=pageViews | where name has "My Page Name" | summarize count() by startofmonth(timestamp))