Sorry this is a bit late this week, I got tangled up in the telephone switch cords! I guess I'm a #WIPWednesday this week. 😁
I wanted to take a moment to talk about my favorite Vanilla feature, the API, and how it can help with analytics. It all comes down to this endpoint, POST/analytics/query
First off, let's talk about why you might want to use the API for this! Our dashboards are great, but there may be situations in which it makes more sense to automate the fetching of analytics data for input into another system, rather than manually generating CSV files for import.
Unlike the majority of the POST endpoints, this does not create or add data. Instead, it requires you to POST the query needed to return analytics data. This query takes the form of a JSON snippet, a sample of which you can see in the screenshot above.
I'm going to show you how to figure out what JSON is needed in your query!
Let's say that we want to grab the Visits per role-type data from the Traffic dashboard. Load the page and then open your browser's dev tools, select the Network tab and refresh the page.
Note that I've filtered the results by the keyword keen and XHR and Fetch.
Now we need to find which fetch is associated with the chart we want - this requires a little trial and error as the fetch events do not necessarily align with where the chart is on the page.
To find the right fetch, click an event and select the Payload tab. As you can see here, I've found the call that groups by user.roleType, which is the chart we want!
And here the fetch is with all the information we need to include in our API call displayed. Note that you won't need to add a filter for siteID to your API call as that will be handled automatically. We also don't need to specify a timezone
Here is the above converted into JSON:
{
"collection": "page",
"type": "count_unique",
"filters": [
{
"prop": "user.roleType",
"op": "in",
"val": [
"guest",
"member",
"cm",
"admin",
"mod"
]
}
],
"group": "user.roleType",
"interval": "monthly",
"property": "user.sessionID",
"start": "2023-01-24T00:00:00",
"end": "2024-01-24T00:00:00"
}
Note that the "filters": key is followed by a square bracket [. This means it contains a list. So if you have multiple filters to add, you can add them all within the square brackets [ ].
This call returns the same data as the chart. Note that it returns a list of objects that includes a timeframe and a list of values that includes roleType and the result.
Like most things with both analytics and the API, you might need to do a little experimenting to get the data you want. But the endpoint is pretty good at returning errors that contain helpful information. Of course, if you don't format the JSON exactly correctly, it'll simple let you know that it can't read it and it will be up to your eagle eyes to find the extra or missing comma.
Let me know if I can provide any further clarity!