Back

Step by Step Guide to Building a Fathom API Integration in PHP

Aug 15, 20247 minute read

Introduction

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.

Prerequisites

Before we jump in, make sure you've got:

  • A PHP environment (7.4+ recommended)
  • Composer installed
  • Your Fathom API key handy

Got all that? Great! Let's get coding.

Setting up the project

First things first, let's set up our project:

mkdir fathom-integration && cd fathom-integration composer init composer require guzzlehttp/guzzle

Authenticating with the Fathom API

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!

Implementing key Fathom API endpoints

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); }

Error handling and rate limiting

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!

Creating a simple dashboard

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";

Optimizing the integration

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); });

Testing the integration

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]); } }

Conclusion

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!

Resources

Now go forth and analyze with confidence!