Introduction to SearchFit API Automation
As AI assistants like ChatGPT, Perplexity, Gemini, and Claude increasingly influence how customers discover brands, monitoring your visibility across these platforms has become essential. However, manually checking your brand mentions and AI recommendations across multiple assistants is time-consuming and inefficient. This is where the SearchFit API comes in.
The SearchFit API enables you to automate AI visibility tracking, generate real-time alerts when your brand is mentioned or recommended by AI assistants, and create comprehensive reports without manual intervention. Whether you're a digital marketing agency managing multiple clients, a B2B SaaS company tracking product visibility, or an e-commerce brand monitoring Shopify product recommendations, API automation streamlines your Answer Engine Optimization (AEO) workflow.
In this comprehensive tutorial, you'll learn how to set up the SearchFit API, authenticate requests, configure automated alerts, generate reports programmatically, and integrate these capabilities into your existing workflows. By the end, you'll have a fully functional automation system that delivers AI visibility insights directly to your team.
Prerequisites and Setup Requirements
Photo by Luke Chesser on Unsplash
Before you begin automating AI visibility alerts and reports with the SearchFit API, ensure you have the following prerequisites in place.
Account and API Access
First, you need an active SearchFit account. Visit SearchFit's website and sign up for an account if you haven't already. Once your account is created, navigate to your API settings dashboard. You'll find your unique API key, which authenticates all your requests to the SearchFit API. Store this key securely, never commit it to public repositories or share it with unauthorized users.
Your API key is the gateway to automating AI visibility tracking. It grants programmatic access to your brand's data, including AI visibility metrics across ChatGPT, Gemini, Perplexity, Claude, and Grok. Keep this key in an environment variable (e.g., SEARCHFIT_API_KEY) rather than hardcoding it into your scripts.
Technical Requirements
You'll need a basic understanding of REST APIs and HTTP requests. Familiarity with JSON is essential, as the SearchFit API communicates using JSON payloads. You should also have access to a programming language or tool for making HTTP requests. Popular options include:
- Python with the
requestslibrary - Node.js with
axiosornode-fetch - cURL for command-line testing
- Postman for interactive API exploration
- Zapier or Make for no-code automation
If you're planning to schedule automated reports, you'll also need access to a task scheduler (like cron on Linux/Mac, Task Scheduler on Windows) or a cloud service like AWS Lambda, Google Cloud Functions, or Zapier.
Understanding SearchFit's AI Visibility Tracking
Before diving into API calls, understand what SearchFit tracks. The platform monitors brand visibility across multiple AI assistants, capturing:
- Brand citations from AI assistants when they mention your company or product
- Recommendation rankings showing how often your brand is recommended for specific queries
- Competitor mentions across AI platforms
- Content attribution tracking which of your pages are being referenced
- Multi-platform metrics for ChatGPT, Perplexity, Gemini, Claude, and Grok
This real-time data is what you'll be automating access to through the API. Understanding these metrics helps you configure meaningful alerts and reports.
Step 1: Authenticate and Test Your API Connection
Photo by Stephen Dawson on Unsplash
Every request to the SearchFit API requires proper authentication. This section walks you through verifying your API credentials and testing your first connection.
Setting Up Environment Variables
Start by securely storing your API key. On your local machine or server, set an environment variable:
On Linux/Mac:
export SEARCHFIT_API_KEY="your-api-key-here"On Windows (PowerShell):
$env:SEARCHFIT_API_KEY="your-api-key-here"In a .env file (for Python/Node.js projects):
SEARCHFIT_API_KEY=your-api-key-here
SEARCHFIT_BASE_URL=https://api.searchfit.ai/v1Never hardcode your API key directly in your source code. Use environment variables or secrets management tools like AWS Secrets Manager, HashiCorp Vault, or GitHub Secrets for production environments.
Testing Authentication with cURL
Test your API connection using cURL, a command-line tool for making HTTP requests:
curl -X GET https://api.searchfit.ai/v1/account \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json"Replace YOUR_API_KEY with your actual API key. A successful response returns your account details in JSON format:
{
"account_id": "acc_123456",
"company_name": "Your Company",
"plan": "professional",
"api_requests_used": 1250,
"api_requests_limit": 10000,
"created_at": "2024-01-15T10:30:00Z"
}If you receive a 401 Unauthorized error, double-check your API key. If you get a 403 Forbidden error, your API plan may not include the endpoint you're accessing.
Testing with Python
For Python-based automation, use the requests library:
import os
import requests
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
api_key = os.getenv('SEARCHFIT_API_KEY')
base_url = 'https://api.searchfit.ai/v1'
# Test authentication
headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
response = requests.get(f'{base_url}/account', headers=headers)
if response.status_code == 200:
print('Authentication successful!')
print(response.json())
else:
print(f'Error: {response.status_code}')
print(response.text)Run this script to verify your API credentials work correctly. You should see your account information printed to the console.
Step 2: Retrieve Your Brand's AI Visibility Data
Photo by 1981 Digital on Unsplash
Now that you're authenticated, retrieve your brand's current AI visibility metrics across all monitored AI assistants.
Getting Brand Visibility Overview
Start by fetching a high-level overview of your brand's visibility:
import requests
import json
from datetime import datetime, timedelta
api_key = os.getenv('SEARCHFIT_API_KEY')
base_url = 'https://api.searchfit.ai/v1'
headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
# Get visibility overview for the last 30 days
params = {
'days': 30,
'include_platforms': ['chatgpt', 'perplexity', 'gemini', 'claude', 'grok']
}
response = requests.get(
f'{base_url}/brands/visibility/overview',
headers=headers,
params=params
)
if response.status_code == 200:
visibility_data = response.json()
print(json.dumps(visibility_data, indent=2))
else:
print(f'Error: {response.status_code} - {response.text}')Expected output shows visibility metrics across platforms:
{
"brand_id": "brand_abc123",
"period": "30_days",
"total_mentions": 1247,
"total_recommendations": 342,
"platforms": {
"chatgpt": {
"mentions": 450,
"recommendations": 120,
"average_position": 2.3,
"growth_percentage": 15.2
},
"perplexity": {
"mentions": 380,
"recommendations": 95,
"average_position": 1.8,
"growth_percentage": 22.5
},
"gemini": {
"mentions": 417,
"recommendations": 127,
"average_position": 2.1,
"growth_percentage": 18.3
}
},
"top_keywords": [
{"keyword": "AI visibility tracking", "mentions": 89, "platform": "chatgpt"},
{"keyword": "AEO platform", "mentions": 76, "platform": "perplexity"},
{"keyword": "multi-platform AI monitoring", "mentions": 65, "platform": "gemini"}
]
}This data shows how often your brand appears across AI assistants, where it ranks, and which keywords drive the most mentions.
Fetching Platform-Specific Details
For deeper analysis, retrieve detailed metrics for a specific AI platform:
# Get detailed ChatGPT visibility metrics
response = requests.get(
f'{base_url}/brands/visibility/chatgpt',
headers=headers,
params={
'days': 30,
'include_keywords': True,
'include_competitors': True
}
)
if response.status_code == 200:
chatgpt_data = response.json()
print(f"ChatGPT Mentions: {chatgpt_data['total_mentions']}")
print(f"Average Position: {chatgpt_data['average_position']}")
print(f"\nTop Keywords:")
for keyword in chatgpt_data['top_keywords'][:5]:
print(f" - {keyword['query']}: {keyword['mentions']} mentions")This endpoint returns platform-specific data, including which queries mention your brand and how your competitors appear in the same contexts.
Step 3: Configure Automated AI Visibility Alerts
With visibility data in hand, set up automated alerts that notify you when significant changes occur or when specific conditions are met.
Creating Alert Rules
Create alert rules that trigger notifications based on your business needs:
# Define alert rules
alert_rules = [
{
"name": "Major Mention Spike",
"type": "mention_threshold",
"platform": "chatgpt",
"threshold": 50,
"period_hours": 24,
"condition": "greater_than",
"notification_channels": ["email", "slack"]
},
{
"name": "Competitor Mentions Increase",
"type": "competitor_comparison",
"platforms": ["chatgpt", "perplexity", "gemini"],
"competitors": ["semrush", "ahrefs", "moz"],
"alert_when": "competitor_exceeds_by_percentage",
"percentage_threshold": 10,
"notification_channels": ["email"]
},
{
"name": "New Keyword Mentions",
"type": "keyword_alert",
"keywords": ["AI visibility tracking", "AEO platform", "answer engine optimization"],
"platforms": ["all"],
"alert_on_first_mention": True,
"notification_channels": ["slack", "webhook"]
},
{
"name": "Ranking Position Drop",
"type": "ranking_change",
"platforms": ["perplexity"],
"alert_when": "position_drops_by",
"position_threshold": 3,
"notification_channels": ["email"]
}
]
# Create each alert rule via API
for rule in alert_rules:
response = requests.post(
f'{base_url}/alerts/rules',
headers=headers,
json=rule
)
if response.status_code == 201:
alert_id = response.json()['alert_id']
print(f"Created alert: {rule['name']} (ID: {alert_id})")
else:
print(f"Failed to create alert {rule['name']}: {response.status_code}")Each alert rule creates a condition that, when met, triggers a notification through your specified channels.
Configuring Notification Channels
Set up how you want to be notified. SearchFit supports multiple channels:
# Configure email notifications
email_config = {
"channel_type": "email",
"enabled": True,
"recipients": [
"[email protected]",
"[email protected]"
],
"digest_frequency": "daily",
"digest_time": "09:00"
}
response = requests.post(
f'{base_url}/notifications/channels',
headers=headers,
json=email_config
)
if response.status_code == 201:
print("Email notifications configured")
# Configure Slack notifications
slack_config = {
"channel_type": "slack",
"enabled": True,
"webhook_url": "https://hooks.slack.com/services/YOUR/WEBHOOK/URL",
"channel": "#ai-visibility",
"mention_on_alert": "@marketing-team"
}
response = requests.post(
f'{base_url}/notifications/channels',
headers=headers,
json=slack_config
)
if response.status_code == 201:
print("Slack notifications configured")Notification channels ensure your team stays informed about important AI visibility changes without manual checking.
Step 4: Generate Automated Reports Programmatically
Automate the creation of comprehensive AI visibility reports that can be scheduled, emailed, or published automatically.
Creating Report Templates
Define report templates that specify what data to include:
# Define a comprehensive AEO report template
report_template = {
"name": "Weekly AI Visibility Report",
"frequency": "weekly",
"day_of_week": "monday",
"time": "09:00",
"sections": [
{
"section_type": "executive_summary",
"include": [
"total_mentions_change",
"total_recommendations_change",
"top_performing_platform",
"key_insights"
]
},
{
"section_type": "platform_breakdown",
"platforms": ["chatgpt", "perplexity", "gemini", "claude", "grok"],
"metrics": [
"mentions_count",
"recommendations_count",
"average_position",
"growth_percentage"
]
},
{
"section_type": "keyword_analysis",
"top_keywords_count": 15,
"include_search_volume": True,
"include_competitor_comparison": True
},
{
"section_type": "competitor_analysis",
"competitors": ["semrush", "ahrefs", "moz"],
"metrics": ["mention_comparison", "ranking_comparison"]
},
{
"section_type": "content_performance",
"include": [
"most_cited_pages",
"pages_with_most_recommendations",
"content_attribution_sources"
]
},
{
"section_type": "recommendations",
"include_aeo_optimization_tips": True,
"include_content_gaps": True
}
],
"output_formats": ["pdf", "html", "json"],
"recipients": {
"email": ["[email protected]", "[email protected]"],
"slack": ["#marketing", "#executive-reports"]
}
}
# Create the report template
response = requests.post(
f'{base_url}/reports/templates',
headers=headers,
json=report_template
)
if response.status_code == 201:
template_id = response.json()['template_id']
print(f"Report template created: {template_id}")
else:
print(f"Error creating template: {response.status_code}")Report templates define the structure and content of automated reports, ensuring consistency and relevance.
Generating On-Demand Reports
Generate reports immediately without waiting for scheduled times:
# Generate an on-demand report
report_request = {
"template_id": "template_abc123",
"date_range": {
"start_date": "2024-01-01",
"end_date": "2024-01-31"
},
"output_format": "pdf",
"include_sections": [
"executive_summary",
"platform_breakdown",
"keyword_analysis"
]
}
response = requests.post(
f'{base_url}/reports/generate',
headers=headers,
json=report_request
)
if response.status_code == 202:
report_job = response.json()
job_id = report_job['job_id']
print(f"Report generation started. Job ID: {job_id}")
# Poll for completion
import time
while True:
status_response = requests.get(
f'{base_url}/reports/jobs/{job_id}',
headers=headers
)
if status_response.status_code == 200:
job_status = status_response.json()
if job_status['status'] == 'completed':
print(f"Report ready: {job_status['download_url']}")
break
elif job_status['status'] == 'failed':
print(f"Report generation failed: {job_status['error']}")
break
else:
print(f"Status: {job_status['status']}...")
time.sleep(5)
else:
print(f"Error: {response.status_code}")This approach lets you generate reports on-demand and track their completion status.
Step 5: Integrate with Automation Platforms
Streamline your workflow by integrating SearchFit API with popular automation platforms. This eliminates the need to write and maintain custom scripts.
Using Zapier for No-Code Automation
Zapier's platform documentation provides comprehensive guidance for building automated workflows. You can create a Zapier integration that:
- Triggers: Monitors SearchFit for specific events (mention spike, new competitor mention, ranking change)
- Actions: Automatically sends Slack messages, creates Google Sheets rows, sends emails, or updates CRM records
- Filters: Applies conditions to decide which events trigger actions
Example Zapier workflow:
- Trigger: SearchFit detects a 50+ mention spike in ChatGPT
- Action: Send Slack message to #marketing channel
- Action: Create a row in Google Sheets with timestamp and details
- Action: Send email to marketing manager
To set this up, you'll authenticate SearchFit in Zapier using your API key, then build a multi-step workflow that connects SearchFit data to your other business tools.
Using Make (Integromat) for Complex Workflows
Make's help center offers detailed documentation for building scenario-based automation. Make allows more complex logic than Zapier:
Scenario: Monitor all AI platforms and compile daily digest
1. Schedule trigger (daily at 8 AM)
2. Call SearchFit API to get ChatGPT visibility
3. Call SearchFit API to get Perplexity visibility
4. Call SearchFit API to get Gemini visibility
5. Transform data into formatted table
6. Send to Google Sheets
7. Send summary to email
8. Post summary to SlackMake's visual scenario builder makes it easy to construct multi-step workflows without coding.
Using n8n for Self-Hosted Automation
For enterprise teams wanting complete control, n8n documentation enables self-hosted workflow automation. Deploy n8n on your own servers and create SearchFit automations:
{
"name": "Daily AI Visibility Report",
"nodes": [
{
"name": "Schedule Trigger",
"type": "cron",
"settings": {
"time": "0 9 * * *"
}
},
{
"name": "Fetch SearchFit Data",
"type": "http",
"settings": {
"url": "https://api.searchfit.ai/v1/brands/visibility/overview",
"method": "GET",
"headers": {
"Authorization": "Bearer {{ $env.SEARCHFIT_API_KEY }}"
}
}
},
{
"name": "Send Email Report",
"type": "emailSend",
"settings": {
"to": "[email protected]",
"subject": "Daily AI Visibility Report",
"html": "{{ $node.FetchSearchFitData.json }}"
}
}
]
}Self-hosted automation gives you full control over data and workflows.
Step 6: Schedule Automated Alert Checks and Reports
Ensure your automation runs consistently by scheduling API calls at regular intervals.
Using Cron Jobs (Linux/Mac)
Create a Python script that runs on a schedule:
#!/usr/bin/env python3
# File: check_ai_visibility.py
import os
import requests
import json
from datetime import datetime
from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv('SEARCHFIT_API_KEY')
base_url = 'https://api.searchfit.ai/v1'
headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
def check_visibility_and_alert():
"""Check AI visibility and trigger alerts if conditions are met"""
# Get current visibility
response = requests.get(
f'{base_url}/brands/visibility/overview',
headers=headers,
params={'days': 1}
)
if response.status_code != 200:
print(f"Error fetching visibility: {response.status_code}")
return
data = response.json()
timestamp = datetime.now().isoformat()
# Log results
log_file = '/var/log/searchfit_monitoring.log'
with open(log_file, 'a') as f:
f.write(f"[{timestamp}] Mentions: {data['total_mentions']}, "
f"Recommendations: {data['total_recommendations']}\n")
# Check if thresholds are exceeded
if data['total_mentions'] > 100:
print(f"Alert: High mention volume detected ({data['total_mentions']})")
# Trigger notification
notify_slack(f"High mention volume: {data['total_mentions']}")
def notify_slack(message):
"""Send notification to Slack"""
webhook_url = os.getenv('SLACK_WEBHOOK_URL')
payload = {'text': message}
requests.post(webhook_url, json=payload)
if __name__ == '__main__':
check_visibility_and_alert()Add this to your crontab to run every hour:
0 * * * * /usr/bin/python3 /home/user/check_ai_visibility.pyThis runs the visibility check at the top of every hour.
Using Windows Task Scheduler
On Windows, create a scheduled task:
- Open Task Scheduler
- Create Basic Task
- Set trigger (e.g., "Daily at 9:00 AM")
- Set action: "Start a program"
- Program:
python.exe - Arguments:
C:\scripts\check_ai_visibility.py
Using Cloud Functions
For cloud-based scheduling without managing servers, use AWS Lambda or Google Cloud Functions:
# AWS Lambda function
import json
import os
import requests
def lambda_handler(event, context):
api_key = os.environ['SEARCHFIT_API_KEY']
base_url = 'https://api.searchfit.ai/v1'
headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
# Fetch visibility data
response = requests.get(
f'{base_url}/brands/visibility/overview',
headers=headers,
params={'days': 1}
)
if response.status_code == 200:
data = response.json()
return {
'statusCode': 200,
'body': json.dumps(data)
}
else:
return {
'statusCode': response.status_code,
'body': response.text
}Deploy this to AWS Lambda and set a CloudWatch event to trigger it hourly. Cloud functions scale automatically and require no server maintenance.
Step 7: Build Custom Dashboards with API Data
Create custom dashboards that visualize your AI visibility data in real-time.
Pushing Data to Google Sheets
Automatically update a Google Sheet with your latest AI visibility metrics:
from google.oauth2.service_account import Credentials
from google.auth.transport.requests import Request
import gspread
import requests
from datetime import datetime
# Authenticate with Google Sheets
scope = ['https://www.googleapis.com/auth/spreadsheets']
creds = Credentials.from_service_account_file(
'google-credentials.json',
scopes=scope
)
client = gspread.authorize(creds)
spreadsheet = client.open('AI Visibility Dashboard')
worksheet = spreadsheet.worksheet('Daily Metrics')
# Fetch SearchFit data
api_key = os.getenv('SEARCHFIT_API_KEY')
headers = {'Authorization': f'Bearer {api_key}'}
response = requests.get(
'https://api.searchfit.ai/v1/brands/visibility/overview',
headers=headers,
params={'days': 1}
)
if response.status_code == 200:
data = response.json()
# Prepare row for Google Sheets
row = [
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
data['total_mentions'],
data['total_recommendations'],
data['platforms']['chatgpt']['mentions'],
data['platforms']['perplexity']['mentions'],
data['platforms']['gemini']['mentions']
]
# Append to worksheet
worksheet.append_row(row)
print("Data updated in Google Sheets")This creates a live-updating spreadsheet that your team can monitor without accessing SearchFit directly.
Building a Custom Web Dashboard
Create a simple web dashboard that displays AI visibility data:
<!DOCTYPE html>
<html>
<head>
<title>AI Visibility Dashboard</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.metric { display: inline-block; margin: 20px; padding: 20px; border: 1px solid #ccc; }
.metric-value { font-size: 32px; font-weight: bold; color: #0066cc; }
.metric-label { color: #666; }
</style>
</head>
<body>
<h1>AI Visibility Dashboard</h1>
<div id="metrics"></div>
<canvas id="chart"></canvas>
<script>
async function fetchVisibilityData() {
const response = await fetch('/api/visibility', {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const data = await response.json();
displayMetrics(data);
displayChart(data);
}
function displayMetrics(data) {
const metricsDiv = document.getElementById('metrics');
metricsDiv.innerHTML = `
<div class="metric">
<div class="metric-label">Total Mentions (30 days)</div>
<div class="metric-value">${data.total_mentions}</div>
</div>
<div class="metric">
<div class="metric-label">Total Recommendations</div>
<div class="metric-value">${data.total_recommendations}</div>
</div>
<div class="metric">
<div class="metric-label">ChatGPT Mentions</div>
<div class="metric-value">${data.platforms.chatgpt.mentions}</div>
</div>
<div class="metric">
<div class="metric-label">Perplexity Mentions</div>
<div class="metric-value">${data.platforms.perplexity.mentions}</div>
</div>
`;
}
function displayChart(data) {
const ctx = document.getElementById('chart').getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels: ['ChatGPT', 'Perplexity', 'Gemini', 'Claude', 'Grok'],
datasets: [{
label: 'Mentions',
data: [
data.platforms.chatgpt.mentions,
data.platforms.perplexity.mentions,
data.platforms.gemini.mentions,
data.platforms.claude.mentions,
data.platforms.grok.mentions
],
backgroundColor: '#0066cc'
}]
}
});
}
// Refresh every 5 minutes
fetchVisibilityData();
setInterval(fetchVisibilityData, 5 * 60 * 1000);
</script>
</body>
</html>This dashboard automatically fetches and displays your latest AI visibility metrics.
Step 8: Integrate SearchFit with Your Existing Tools
Connect SearchFit API data to platforms your team already uses.
Integrating with HubSpot CRM
Automatically create deals or contacts based on AI visibility insights:
import requests
import json
# Get SearchFit data
searchfit_response = requests.get(
'https://api.searchfit.ai/v1/brands/visibility/overview',
headers={'Authorization': f'Bearer {api_key}'},
params={'days': 7}
)
data = searchfit_response.json()
# Create HubSpot deal if visibility increased significantly
if data['platforms']['chatgpt']['growth_percentage'] > 20:
hubspot_payload = {
'properties': {
'dealname': 'AI Visibility Spike - ChatGPT",
'dealstage': 'negotiation',
'amount': 5000,
'description': f"ChatGPT mentions increased {data['platforms']['chatgpt']['growth_percentage']}%",
'closedate': datetime.now().isoformat()
}
}
hubspot_response = requests.post(
'https://api.hubapi.com/crm/v3/objects/deals',
headers={
'Authorization': f'Bearer {hubspot_api_key}',
'Content-Type': 'application/json'
},
json=hubspot_payload
)This automatically logs significant AI visibility changes in your CRM.
Integrating with Slack Workflows
Use Slack's REST API to post detailed AI visibility summaries:
import requests
import json
from datetime import datetime
def post_daily_summary_to_slack():
api_key = os.getenv('SEARCHFIT_API_KEY')
slack_webhook = os.getenv('SLACK_WEBHOOK_URL')
# Get visibility data
response = requests.get(
'https://api.searchfit.ai/v1/brands/visibility/overview',
headers={'Authorization': f'Bearer {api_key}'},
params={'days': 1}
)
data = response.json()
# Format Slack message
message = {
'blocks': [
{
'type': 'header',
'text': {
'type': 'plain_text',
'text': '📊 Daily AI Visibility Report'
}
},
{
'type': 'section',
'fields': [
{
'type': 'mrkdwn',
'text': f"*Total Mentions*\n{data['total_mentions']}"
},
{
'type': 'mrkdwn',
'text': f"*Total Recommendations*\n{data['total_recommendations']}"
},
{
'type': 'mrkdwn',
'text': f"*ChatGPT Mentions*\n{data['platforms']['chatgpt']['mentions']}"
},
{
'type': 'mrkdwn',
'text': f"*Perplexity Mentions*\n{data['platforms']['perplexity']['mentions']}"
}
]
}
]
}
# Post to Slack
requests.post(slack_webhook, json=message)This sends a formatted, visually appealing daily summary to your team.
Step 9: Troubleshooting Common Issues
When working with the SearchFit API, you may encounter common issues. Here's how to resolve them.
Authentication Errors
Problem: "401 Unauthorized" error
Solutions:
- Verify your API key is correct and hasn't expired
- Check that the API key is being passed in the
Authorization: Bearerheader - Ensure your API key is stored as an environment variable, not hardcoded
- Confirm your API plan includes access to the endpoint you're calling
Problem: "403 Forbidden" error
Solutions:
- Your API plan may not include the endpoint
- Check your account plan at SearchFit's dashboard
- Contact SearchFit support if you believe you should have access
Rate Limiting
Problem: "429 Too Many Requests" error
Solutions:
- Implement exponential backoff in your code:
import time
def make_request_with_retry(url, headers, max_retries=3):
for attempt in range(max_retries):
response = requests.get(url, headers=headers)
if response.status_code == 429:
wait_time = 2 ** attempt # Exponential backoff: 1s, 2s, 4s
print(f"Rate limited. Waiting {wait_time} seconds...")
time.sleep(wait_time)
else:
return response
raise Exception("Max retries exceeded")- Check your API usage at SearchFit's dashboard
- Upgrade your plan if you consistently hit rate limits
- Cache results locally to reduce API calls
Data Inconsistencies
Problem: API returns different data on subsequent calls
Solutions:
- AI visibility data updates continuously; use consistent time windows
- Specify exact date ranges in API calls:
response = requests.get(
'https://api.searchfit.ai/v1/brands/visibility/overview',
headers=headers,
params={
'start_date': '2024-01-01',
'end_date': '2024-01-31'
}
)- Allow time for data processing (SearchFit processes mentions with slight delays)
Connection Timeouts
Problem: Requests timeout when fetching large reports
Solutions:
- Increase timeout values:
response = requests.get(
url,
headers=headers,
timeout=30 # 30 second timeout
)- Use asynchronous requests for parallel processing:
import asyncio
import aiohttp
async def fetch_multiple_platforms():
async with aiohttp.ClientSession() as session:
platforms = ['chatgpt', 'perplexity', 'gemini']
tasks = [
fetch_platform_data(session, platform)
for platform in platforms
]
return await asyncio.gather(*tasks)- Request data generation as a background job instead of waiting:
# Request report generation
response = requests.post(
'https://api.searchfit.ai/v1/reports/generate',
headers=headers,
json=report_config
)
if response.status_code == 202: # Accepted
job_id = response.json()['job_id']
# Check status laterAdvanced Use Cases and Best Practices
Once you've mastered basic automation, explore advanced patterns.
Building a Custom AEO Agent
Create an AI agent that monitors AI visibility and generates optimization recommendations. This is particularly useful for agencies implementing AEO strategies or B2B SaaS teams optimizing content.
Multi-Brand Monitoring
Monitor multiple brands or clients from a single automation system:
def monitor_all_brands():
# Get list of all brands in account
response = requests.get(
'https://api.searchfit.ai/v1/brands',
headers=headers
)
brands = response.json()['brands']
for brand in brands:
brand_id = brand['id']
# Get visibility for each brand
visibility = requests.get(
f'https://api.searchfit.ai/v1/brands/{brand_id}/visibility',
headers=headers
).json()
# Compare to previous period
previous = get_previous_period_data(brand_id)
# Generate alert if significant change
if visibility['total_mentions'] > previous['total_mentions'] * 1.5:
alert_team(f"Significant visibility increase for {brand['name']}")Competitor Intelligence Automation
Automatically track when competitors appear in the same AI responses as your brand:
def analyze_competitive_landscape():
# Get queries where your brand appears
response = requests.get(
'https://api.searchfit.ai/v1/brands/mentions/queries',
headers=headers,
params={'limit': 100}
)
queries = response.json()['queries']
for query in queries:
# Check which competitors appear for same query
competitors_response = requests.get(
'https://api.searchfit.ai/v1/competitors/mentions',
headers=headers,
params={'query': query['text'], 'platforms': 'chatgpt'}
)
competitors = competitors_response.json()['competitors']
# Log competitive insights
store_competitive_insight({
'query': query['text'],
'your_brand_mentions': query['mentions'],
'competing_brands': [c['name'] for c in competitors]
})Conclusion
Automating AI visibility alerts and reports with the SearchFit API transforms how you monitor and optimize for Answer Engine Optimization. By following this tutorial, you've learned how to:
- Authenticate and test API connections
- Retrieve comprehensive AI visibility data across ChatGPT, Perplexity, Gemini, Claude, and Grok
- Configure intelligent alert rules that notify your team of important changes
- Generate automated reports on schedules that work for your business
- Integrate with automation platforms like Zapier, Make, and n8n
- Build custom dashboards and integrations with your existing tools
- Troubleshoot common issues and implement best practices
With these automation capabilities, you can focus on strategy and optimization rather than manual monitoring. Your team will receive timely alerts about AI visibility changes, comprehensive reports will be generated automatically, and your entire workflow will be streamlined.
For deeper dives into specific topics, explore how to track AI visibility across multiple platforms, optimize your content for answer engines, or review SearchFit's comprehensive AEO guide.
Start with simple automations (perhaps a daily email report) and gradually build more sophisticated workflows as you become comfortable with the API. The SearchFit API documentation and community support are available to help you at every step of your automation journey.
As you implement these automations, you'll discover new ways to leverage AI visibility data for competitive advantage. The platforms and patterns covered in this tutorial provide a foundation for building whatever custom solutions your business needs.