Whenever we create any News or Page we need some sort of analytics like how users interact with your page or news post. For example, I need information such as total number of people who have viewed the page, the number of unique viewers of the page, average time spent on the page per user, page traffic in a timely manner, and so on.
All this information we can get by clicking on Views in the SitePage.
Ever wonder how we can get all the above information from SharePoint API?
We will be needing several GUID:
1) SiteGUID: GUID of the Site, you can get through API
https://contoso.sharepoint.com/sites/{SiteName}/_api/site/id
2) WebGUID: Web GUID of the site, you can get through API
https://contoso.sharepoint.com/sites/{SiteName}/_api/web/id
3) SityePageGUID: GUID of the SitePage library, you can get through API
https://contoso.sharepoint.com/sites/{SiteName}/_api/web/lists/GetByTitle(%27Site%20Pages%27)/id
4) UniqueID: It is the UniqueId of the SitePage, you can get through API
https://contoso.sharepoint.com/sites/{SiteName}/_api/web/lists/GetByTitle(%27Site%20Pages%27)/items({Id})?$select=Id,Title,UniqueId
Now, If you want to fetch only the number of viewers of the page and unique viewer count for allTime and lastSevenDays we can use below API
GET https://contoso.sharepoint.com/sites/{SiteName}/_api/v2.1/sites/contoso.sharepoint.com,{SiteGUID},{webGUID}/lists/%7B{SitePageGUID}%7D/items/{SitePageUniqueId(GUID)}/driveItem?$select=id,analytics&$expand=analytics($expand=allTime)
If you need to drill down the report as lastThirtyDays, lastNinetyDays, hourly report, average time spent, and much more, we need another API as below.
GET https://contoso.sharepoint.com/sites/{SiteName}/_api/v2.1/sites/contoso.sharepoint.com,{SiteGUID},{webGUID}/lists/%7B{SitePageGUID}%7D/items/{SitePageUniqueId(GUID)}/oneDrive.getAggregatedAnalytics?startDateTime={Today-90Days}&endDateTime={Today}&$expand=accessStatsByDay($expand=lastSevenDays,lastThirtyDays,lastNinetyDays,allTime,itemActivityStats)&select=*
<!--Example : How to pass startDateTime and endDateTime-->
GET https://contoso.sharepoint.com/sites/{SiteName}/_api/v2.1/sites/contoso.sharepoint.com,{SiteGUID},{webGUID}/lists/%7B{SitePageGUID}%7D/items/{SitePageUniqueId(GUID)}/oneDrive.getAggregatedAnalytics?startDateTime=2022-07-11T06:47:52.748Z&endDateTime=2022-10-08T06:47:52.748Z&$expand=accessStatsByDay($expand=lastSevenDays,lastThirtyDays,lastNinetyDays,allTime,itemActivityStats)&select=*
Note:
SharePoint also includes guest and anonymous views.
Above information is displayed based on Coordinated Universal Time (UTC).
A very small amount of time is not included in the report for average time spent.