Software geeks: How Matomo automatically generates the API, using PHP Reflection

Contents

Friendly warning: blog post for software geeks only!

What is an “API” in Matomo and how to use it?

In Matomo (Piwik), every plugin can expose its own API. Creating an API in a Matomo plugin is as easy as creating a class in a file called API.php; see example of the UserCountry/API.php API.

This class is then automatically loaded in Matomo and the public methods of the class are automatically available to call as a REST web service. For example, to call the method

public function getCountry( $idSite, $period, $date )

You can simply call:

index.php?module=API&method=UserCountry.getCountry&idSite=1&period=day&date=yesterday&format=xml&token_auth=X

You can see that the parameters idSite, date and period are automatically mapped from the URL to the original php function. This is where the magic happens, using the PHP Reflection API.

The page piwik/index.php?module=API&action=listAllAPI, available from the “API” link in the top bar of the Matomo user interface, will load all plugins API files, and automatically generate the “documentation”, with example links to the calls.

How is this automatic REST API implemented in PHP5?

I have published a quick presentation about the concept behind the implementation of this API code. Here is the embed presentation:

You can also see the presentation on slideshare: “Easy rest service using PHP reflection api – on slideshare”

All the code used for this API functionality is located in piwik/core/API/* ; you can browse this code online in the Matomo code browser. Feel free to reuse this code in your project, and submit any patch that you may have to the Matomo team.

If you’re interested by this topic, see also the blog post: How to design an API?

Let us know your feedback or questions.

Enjoyed this post?
Join the 160,000+ subscribers who receive the Matomo Newsletter straight to their inbox every month
Get started with Matomo

A powerful web analytics platform that gives you and your business 100% data ownership and user privacy protection.

No credit card required.

Free forever.

Get started with Matomo

A powerful web analytics platform that gives you and your business 100% data ownership and user privacy protection.

No credit card required.

Free forever.