Hey there, fellow developer! Ready to dive into the world of Fathom Analytics? If you're looking to integrate this privacy-focused analytics tool into your PHP project, you're in the right place. We'll walk through building a solid Fathom API integration that'll have you pulling site data like a pro in no time.
Before we jump in, make sure you've got:
Got all that? Great! Let's get coding.
First things first, let's set up our project:
mkdir fathom-integration && cd fathom-integration composer init composer require guzzlehttp/guzzle
Now, let's create a simple client to authenticate with Fathom:
<?php require 'vendor/autoload.php'; use GuzzleHttp\Client; $apiKey = 'YOUR_API_KEY'; $client = new Client([ 'base_uri' => 'https://api.usefathom.com/v1/', 'headers' => [ 'Authorization' => "Bearer $apiKey", 'Accept' => 'application/json', ], ]);
Pro tip: In a real-world scenario, you'd want to store that API key in an environment variable. Keep it secret, keep it safe!
Let's create some functions to interact with Fathom's API:
function getSites($client) { $response = $client->get('sites'); return json_decode($response->getBody(), true); } function getAggregatedStats($client, $siteId, $from, $to) { $response = $client->get("aggregations", [ 'query' => [ 'site_id' => $siteId, 'from' => $from, 'to' => $to, 'entity' => 'pageview', 'aggregates' => 'visits,uniques,pageviews,avg_duration,bounce_rate' ] ]); return json_decode($response->getBody(), true); } function getCurrentVisitors($client, $siteId) { $response = $client->get("current_visitors", [ 'query' => ['site_id' => $siteId] ]); return json_decode($response->getBody(), true); }
Let's add some basic error handling:
use GuzzleHttp\Exception\RequestException; try { $sites = getSites($client); } catch (RequestException $e) { echo "Error: " . $e->getMessage(); }
For rate limiting, Fathom is pretty generous, but it's always good to keep an eye on those headers!
Now, let's put it all together in a basic dashboard:
$sites = getSites($client); $siteId = $sites[0]['id']; // Using the first site for this example $from = date('Y-m-d', strtotime('-30 days')); $to = date('Y-m-d'); $stats = getAggregatedStats($client, $siteId, $from, $to); $currentVisitors = getCurrentVisitors($client, $siteId); echo "Site: " . $sites[0]['name'] . "\n"; echo "Visits (last 30 days): " . $stats['visits'] . "\n"; echo "Current visitors: " . $currentVisitors['count'] . "\n";
To take this to the next level, consider implementing caching for your API responses. It'll help you stay within rate limits and speed up your app. A simple file-based cache could look like this:
function getCachedData($key, $ttl, $callback) { $cacheFile = "cache/$key.json"; if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < $ttl)) { return json_decode(file_get_contents($cacheFile), true); } $data = $callback(); file_put_contents($cacheFile, json_encode($data)); return $data; } // Usage $sites = getCachedData('sites', 3600, function() use ($client) { return getSites($client); });
Don't forget to test! Here's a quick PHPUnit test to get you started:
use PHPUnit\Framework\TestCase; class FathomIntegrationTest extends TestCase { public function testGetSites() { $client = $this->createMock(Client::class); $client->method('get') ->willReturn(new Response(200, [], json_encode([['id' => '123', 'name' => 'Test Site']]))); $sites = getSites($client); $this->assertIsArray($sites); $this->assertArrayHasKey('id', $sites[0]); $this->assertArrayHasKey('name', $sites[0]); } }
And there you have it! You've just built a solid foundation for a Fathom API integration in PHP. From here, you can expand on this to create more complex dashboards, automate reporting, or even build your own analytics frontend.
Remember, the key to a great integration is understanding the API, handling errors gracefully, and optimizing for performance. Keep exploring the Fathom API docs for more endpoints and data you can leverage.
Happy coding, and may your bounce rates be low and your conversions high!
Now go forth and analyze with confidence!