Software geeks: How Piwik automatically generates the API, using PHP Reflection
Friendly warning: blog post for software geeks only!
What is an “API” in Piwik and how to use it?
In Piwik, every plugin can expose its own API. Creating an API in a Piwik 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 Piwik 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:
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 Piwik 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 functionnality is located in piwik/core/API/* ; you can browse this code online in the Piwik code browser. Feel free to reuse this code in your project, and submit any patch that you may have to the Piwik 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.