Back

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

Aug 15, 20246 minute read

Hey there, fellow developer! Ready to dive into the world of Fathom API integration? Let's roll up our sleeves and get our hands dirty with some Python code. This guide will walk you through the process of building a robust Fathom API integration, assuming you're already familiar with Python and API basics. Let's get started!

Prerequisites

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

  • Python 3.7+
  • requests library
  • A Fathom API key (if you don't have one, hop over to your Fathom dashboard and grab it)

Setting Up the Environment

First things first, let's get our environment ready:

pip install requests

Now, let's set up our API credentials:

import os os.environ['FATHOM_API_KEY'] = 'your_api_key_here'

Basic API Connection

Let's create a simple client to test our connection:

import requests class FathomClient: BASE_URL = 'https://api.usefathom.com/v1' def __init__(self): self.api_key = os.environ.get('FATHOM_API_KEY') self.session = requests.Session() self.session.headers.update({'Authorization': f'Bearer {self.api_key}'}) def test_connection(self): response = self.session.get(f'{self.BASE_URL}/account') return response.json() client = FathomClient() print(client.test_connection())

If everything's set up correctly, you should see your account details. Nice work!

Fetching Data

Now, let's grab some site statistics:

def get_site_stats(self, site_id, date_from, date_to): params = { 'entity': 'pageview', 'entity_id': site_id, 'date_from': date_from, 'date_to': date_to, 'aggregates': 'visits,uniques,pageviews,avg_duration,bounce_rate' } response = self.session.get(f'{self.BASE_URL}/aggregations', params=params) return response.json()

Data Processing

Let's parse that JSON and extract the good stuff:

def process_site_stats(self, stats): return { 'visits': stats['visits']['value'], 'uniques': stats['uniques']['value'], 'pageviews': stats['pageviews']['value'], 'avg_duration': stats['avg_duration']['value'], 'bounce_rate': stats['bounce_rate']['value'] }

Building Core Functionalities

Time to implement some key endpoints and add error handling:

import time def get_sites(self): response = self.session.get(f'{self.BASE_URL}/sites') if response.status_code == 429: time.sleep(int(response.headers.get('Retry-After', 5))) return self.get_sites() response.raise_for_status() return response.json()

Creating a Reusable Class

Let's wrap it all up in a neat package:

class FathomAPI: # ... (previous code here) def get_site_stats(self, site_id, date_from, date_to): stats = self._get_site_stats(site_id, date_from, date_to) return self.process_site_stats(stats) def get_all_sites_stats(self, date_from, date_to): sites = self.get_sites() return {site['id']: self.get_site_stats(site['id'], date_from, date_to) for site in sites}

Advanced Usage

Want to kick it up a notch? Let's add some async magic:

import asyncio import aiohttp class AsyncFathomAPI(FathomAPI): async def get_all_sites_stats_async(self, date_from, date_to): sites = await self.get_sites_async() async with aiohttp.ClientSession() as session: tasks = [self.get_site_stats_async(session, site['id'], date_from, date_to) for site in sites] return await asyncio.gather(*tasks) # ... (implement get_sites_async and get_site_stats_async methods)

Testing and Validation

Don't forget to test your code! Here's a quick example using unittest:

import unittest from unittest.mock import patch class TestFathomAPI(unittest.TestCase): @patch('requests.Session.get') def test_get_sites(self, mock_get): mock_get.return_value.json.return_value = [{'id': 'test_site'}] client = FathomAPI() sites = client.get_sites() self.assertEqual(len(sites), 1) self.assertEqual(sites[0]['id'], 'test_site') # ... (add more tests)

Optimization Techniques

To keep things speedy, consider implementing a simple cache:

from functools import lru_cache class CachedFathomAPI(FathomAPI): @lru_cache(maxsize=100) def get_site_stats(self, site_id, date_from, date_to): return super().get_site_stats(site_id, date_from, date_to)

Wrapping Up

And there you have it! You've just built a solid Fathom API integration in Python. From basic connection to advanced async operations and caching, you're now equipped to harness the power of Fathom's analytics in your Python projects.

Remember, this is just the beginning. There's always room for improvement and expansion. Why not try implementing more endpoints or building a CLI tool around this integration?

Keep coding, keep learning, and most importantly, have fun with it! If you hit any snags, the Fathom API docs are your best friend. Happy coding!