Tuesday 8 December 2020

Get gitlab browsing statistics for your project

Unlike github, gitlab doesn't provide a web page to see the browsing activity on your project. But there is an API to fetch this information in JSON format. I explain how it's done so you can avoid the pitfalls I encountered.

In the documentation, all the API calls are with respect to a base URL, which is currently:

https://gitlab.com/api/v4

This StackOverflow post confirms this base URL. It also shows how the access token is passed to the GET request, as an extra header.

Getting a personal access token is described here with screenshots. You can set an expiry date for the token. Make sure you save a copy of it as you cannot see it again once generated.

Now if you look at the API documentation, the relative URL to get the statistics for the last 30 days is described here and is:

/projects/:id/statistics

This is where I got fooled. The : is not to be entered literally. Instead substitute the numeric ID of your project.

Putting it all together, here is the curl command to get the statistics for a fictional project ID of 1234.

curl -H 'PRIVATE-TOKEN: yourtokenhere' https://gitlab.com/api/v4/projects/1234/statistics

And here is typical output:

{"fetches":{"total":3,"days":[{"count":3,"date":"2020-11-23"}]}}

There is no newline at the end, JSON doesn't need it. But you'll be using some other utility to parse and display the statistics in a user-friendly form.

Now you can use this information to get all the other information exposed by the API. Some relative URLs don't require authentication if the project is public.