Hey there, fellow developer! Ready to dive into the world of Fathom analytics? If you're looking to harness the power of Fathom's API in your JavaScript projects, you've come to the right place. In this guide, we'll walk through building a robust Fathom API integration that'll have you crunching those sweet, sweet analytics numbers in no time.
Before we jump in, make sure you've got:
Let's get this show on the road! First things first:
mkdir fathom-api-integration cd fathom-api-integration npm init -y npm install axios dotenv
Boom! Project initialized and dependencies installed. We're using axios
for HTTP requests and dotenv
to keep our API key safe and sound.
Security first! Create a .env
file in your project root:
FATHOM_API_KEY=your_api_key_here
Now, let's create an authenticated API client:
require('dotenv').config(); const axios = require('axios'); const client = axios.create({ baseURL: 'https://api.usefathom.com/v1', headers: { 'Authorization': `Bearer ${process.env.FATHOM_API_KEY}` } });
Time to fetch some data! Let's start with grabbing site information:
async function getSites() { try { const response = await client.get('/sites'); return response.data; } catch (error) { console.error('Error fetching sites:', error.message); } }
Parsing responses is a breeze with axios, but let's add some error handling:
async function getAnalytics(siteId, from, to) { try { const response = await client.get('/aggregations', { params: { site_id: siteId, from, to } }); return response.data; } catch (error) { if (error.response) { console.error('API error:', error.response.data); } else { console.error('Request error:', error.message); } } }
Want to aggregate data across multiple sites? No problem:
async function getAggregatedAnalytics(siteIds, from, to) { const promises = siteIds.map(id => getAnalytics(id, from, to)); const results = await Promise.all(promises); // Aggregate results here return results.reduce((acc, curr) => { // Your aggregation logic }, {}); }
Let's be good API citizens and implement some rate limiting:
const rateLimit = require('axios-rate-limit'); const client = rateLimit(axios.create({ baseURL: 'https://api.usefathom.com/v1', headers: { 'Authorization': `Bearer ${process.env.FATHOM_API_KEY}` } }), { maxRequests: 5, perMilliseconds: 1000 });
Don't forget to test! Here's a quick Jest test to get you started:
test('getSites returns an array', async () => { const sites = await getSites(); expect(Array.isArray(sites)).toBe(true); });
And there you have it! You've just built a solid Fathom API integration. From here, sky's the limit – maybe build a custom dashboard or integrate these analytics into your CI/CD pipeline?
Remember, the Fathom community is super helpful if you get stuck. Now go forth and analyze!