Hey there, fellow developer! Ready to dive into the world of Fathom analytics? In this guide, we'll walk through building a slick C# integration with the Fathom API. Whether you're looking to pull site data, crunch some numbers, or just flex your API muscles, we've got you covered.
Before we jump in, make sure you've got:
Let's get this show on the road:
dotnet add package Newtonsoft.Json
dotnet add package Microsoft.Extensions.Http
Now, let's set up our HTTP client:
using System.Net.Http; using System.Net.Http.Headers; var client = new HttpClient(); client.BaseAddress = new Uri("https://api.usefathom.com/v1/"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "YOUR_API_KEY_HERE");
Let's write a method to fetch site data:
async Task<string> GetSiteData(string siteId) { var response = await client.GetAsync($"sites/{siteId}"); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); }
Always be prepared for the unexpected:
async Task<string> MakeApiCall(string endpoint) { for (int i = 0; i < 3; i++) { try { var response = await client.GetAsync(endpoint); if ((int)response.StatusCode == 429) { await Task.Delay(1000); // Wait a second before retrying continue; } response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } catch (HttpRequestException e) { Console.WriteLine($"Attempt {i + 1} failed: {e.Message}"); } } throw new Exception("API call failed after 3 attempts"); }
Let's parse that JSON:
using Newtonsoft.Json.Linq; var siteData = JObject.Parse(await GetSiteData("SITE_ID")); Console.WriteLine($"Site name: {siteData["name"]}");
Time to make it interactive:
while (true) { Console.Write("Enter site ID (or 'quit' to exit): "); var input = Console.ReadLine(); if (input.ToLower() == "quit") break; var data = await GetSiteData(input); Console.WriteLine(data); }
Let's speed things up with some async magic:
var tasks = new List<Task<string>>(); foreach (var siteId in siteIds) { tasks.Add(GetSiteData(siteId)); } var results = await Task.WhenAll(tasks);
Don't forget to test! Here's a simple unit test to get you started:
[Fact] public async Task GetSiteData_ReturnsValidJson() { var result = await GetSiteData("TEST_SITE_ID"); Assert.True(JObject.Parse(result).HasValues); }
And there you have it! You've just built a solid foundation for your Fathom API integration. Remember, this is just the beginning - there's a whole world of analytics data out there waiting for you to explore. Why not try fetching some time-based stats next, or maybe build a dashboard to visualize your data?
Happy coding, and may your analytics always be insightful!