Chartbeat API PHP Library Sketch

I wasn’t quite sure if there existed a PHP library for the awesome Chartbeat API. (Chartbeat is a realtime analytics engine that we use at Grist, and with which I’ve been playing around just now) so I decided to just start writing one … I’ve so far only gotten as far as erecting the framework and the one call that I happen to need now — namely quickstats().

I might keep adding to this if I have time.

 * Chartbeat Library
 * requires cURL
 * by Matt Perry

class Chartbeat {

public $apikey = '';
public $host = '';

public function __construct($apikey, $host) {

$this->apikey = $apikey;
 $this->host = $host;

if (!$apikey || !$host) {
 throw new Exception('Missing API key or Host');
 //for now we require cURL ... if it's not compiled into PHP, raise exception
 if (!function_exists('curl_init')){
 throw new Exception('Curl not installed');
 return false;

public function quickstats($path = '') {

$url = "{$this->host}&apikey={$this->apikey}";
 if ($path) $url .= "&$path";
 return $this->_do_request($url);

//makes request, decodes json
 private function _do_request($url) {
 $result = $this->_make_call($url);
 $result = json_decode($result);
 return $result;

//makes call with curl
 private function _make_call($url) {

$ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_TIMEOUT, $this->chartbeat_timeout);
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //don't worry about cert problems

$output = curl_exec($ch);

return $output;


Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s