SPFx – Azure Application Insights API


In this post, we will see what is Azure Application Insights, its benefits and features, what kind of data to be explored from Azure Application Insights and how to access the data in SPFx using Azure Application Insights API.

What is Azure Application Insights?

It’s a feature of Azure Monitor service, which provides us with an extensible Application Performance Management service for developers and DevOps professionals. It works for a variety of apps of different technologies which include .Net, Node.js, Java, Python, etc hosted on-premise, hybrid, or completely in the cloud. It provides us a powerful analytics tool to monitor the issues, performance, what users accessing the most in the application, which helps to enhance the application to make it better and better for the end-users and to increase user engagement.

What does Azure Application Insights Monitor?

  • Request rates, response times and failure rates
  • Dependency rates, response times and failure rates
  • Exceptions
  • Pageviews and load performance
  • AJAX calls
  • User and session counts
  • Performance counters
  • Host diagnostics
  • Diagnostic trace logs
  • Custom events and metrics

How do I explore the data?

The data can be explored or analyzed using Azure portal which is the easiest way. Using the Azure portal, the data can be analyzed in charts and in other formats, export to the local disk to analyze further and to generate reports. All the above can be done as long as the user has the respective permissions, in real world not all the users would have access to those information. Azure also offers REST API to explore the data, where the developers can build an application to access the data and the application can be accessed by all the administrators or top level users for reports.

How do I use the REST API? Where can I found the Url?

Microsoft had provided separate documentation for accessing the Azure Application Insights API and also they had provided us the API Explorer for us to explore the API endpoints, response schema, etc. 
Please click here for the full documentation.

Following are the key things to be focussed

  • Quickstart – Provides the document on how to get access to the insights data from REST API and what are all the data can be explored from the API
  • API Reference – Provides the document on security, URL parameters, response schema, and exceptions.
  • API Explorer – Provides a way for the developers to play around the API to understand the response schema and different parameters that can be passed to the API.
  • Documentation – Full documentation on each API and its response data with examples.

Let us see how we can access the data using REST API in SharePoint Framework Webpart (SPFx). The below code focus on accessing the data from API, how to use the query to fetch the data from API. All boiler plate code to create the web part and other stuff are not included.

Microsoft had provided the API explorer for trying out the query and schema and how to pass the query to the API. Please Click here to access the explorer


Below are some of the key params required to access the API.

  • Application ID Application ID of the Azure Application Insights API Access.
  • Application Key Application Key of the Azure Application Insights API Access.

Both the above mentioned ID and Key can be found from the Application Insights resource from Azure Portal.

Once the above information were captured, we can start using the ID and Key to fetch the data.

The below code is a sample to fetch the data based on the query, timespan

public getResponseByQuery = async (query: string, useTimespan: boolean, timespan?: TimeSpan): Promise<any[]> => {
        let finalRes: any[] = [];
        let urlQuery: string = useTimespan ? `timespan=${timespan}&query=${encodeURIComponent(query)}` : `query=${encodeURIComponent(query)}`;
        let finalPostUrl: string = this._postUrl + `/query?${urlQuery}`;
        let responseJson: any = await this.getAPIResponse(finalPostUrl);
        if (responseJson.tables.length > 0) {
            finalRes = responseJson.tables[0].rows;
        return finalRes;

Below are the params and enums used in the above code to fetch the user statistics data.

this._postUrl = "https://api.applicationinsights.io/v1/apps"
query = `union pageViews,customEvents
                | summarize Users=dcount(user_Id) by bin(timestamp, 1h)
                | order by timestamp asc`

export enum TimeSpan {
    "1 hour" = "PT1H",
    "6 hours" = "PT6H",
    "12 hours" = "PT12H",
    "1 day" = "P1D",
    "3 days" = "P3D",
    "7 days" = "P7D",
    "15 days" = "P15D",
    "30 days" = "P30D",
    "45 days" = "P45D",
    "60 days" = "P60D",
    "75 days" = "P75D",
    "90 days" = "P90D",

export enum TimeInterval {
    "30 Min" = "PT30M",
    "1 Hour" = "PT1H",
    "3 Hour" = "PT3H",
    "12 Hour" = "PT12H",
    "1 Day" = "P1D",
    "5 Day" = "P5D"

Few of the statistics like ‘PageViewCount’, ‘PageViews’ etc can be fetched based on the query, timespan and timeinterval. Some of the samples are mentioned below.

public getPageViewCount = async (timespan: TimeSpan, timeinterval: TimeInterval): Promise<IPageViewCountProps[]> => {
        let finalRes: IPageViewCountProps[] = [];
        let finalPostUrl: string = this._postUrl + `/metrics/pageViews/count?timespan=${timespan}&interval=${timeinterval}`;
        let response: HttpClientResponse = await this.httpClient.get(finalPostUrl, HttpClient.configurations.v1, this.httpClientOptions);
        let responseJson: any = await response.json();
        if (responseJson.value && responseJson.value.segments.length > 0) {
            let segments: any[] = responseJson.value.segments;
            segments.map((seg: any) => {
                    oriDate: seg.start,
                    date: this.getLocalTime(seg.start),
                    sum: seg['pageViews/count'].sum
        return finalRes;
public getPageViews = async (timespan: TimeSpan, timeinterval: TimeInterval, segment: Segments[]): Promise<IPageViewDetailProps[]> => {
        let finalRes: IPageViewDetailProps[] = [];
        let finalPostUrl: string = this._postUrl + `/metrics/pageViews/count?timespan=${timespan}&interval=${timeinterval}&segment=${encodeURIComponent(segment.join(','))}`;
        let response: HttpClientResponse = await this.httpClient.get(finalPostUrl, HttpClient.configurations.v1, this.httpClientOptions);
        let responseJson: any = await response.json();
        if (responseJson.value && responseJson.value.segments.length > 0) {
            let mainSegments: any[] = responseJson.value.segments;
            mainSegments.map(mainseg => {
                if (mainseg.segments.length > 0) {
                    mainseg.segments.map((seg: any) => {
                            oriStartDate: mainseg.start,
                            oriEndDate: mainseg.end,
                            start: this.getFormattedDate(mainseg.start),
                            end: this.getFormattedDate(mainseg.end),
                            date: `${this.getFormattedDate(mainseg.start)} - ${this.getFormattedDate(mainseg.end)}`,
                            Url: seg[segment[0]],
                            count: seg['pageViews/count'].sum
        return finalRes;

I had also used the above steps and created a App Insights Dashboard web part which is shared via the PnP/SPFxWebparts community and also shared some posts on how to add the data to App Insights. Don’t forget to check the below links

Happy Coding…


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s