Fetch Website Analytics Using Plausible API
Set up a Python script to fetch website analytics data from Plausible Analytics using the Plausible API
Prerequisite You should have an API key from Plausible Analytics and have it stored in a .env file.
Introduction
This guide demonstrates how to set up a Python script to fetch website analytics data from Plausible Analytics using the Plausible API. You’ll learn how to install the necessary library, set up your environment, and create a simple script to fetch and display analytics data.
Setup
Step 1: Install Required Packages
First, install the necessary packages using pip:
pip install requests python-dotenv
Step 2: Create a .env File
Create a .env
file in the project root with your Plausible API key:
PLAUSIBLE_API_KEY=your_plausible_api_key
Step 3: Create the Python Script
Create a Python script named fetch_plausible_analytics.py
with the following content:
import requests
import json
import os
from dotenv import load_dotenv
from datetime import datetime, timedelta
# Load environment variables from .env file
load_dotenv()
# Access the API key from environment variables
plausible_api_key = os.getenv('PLAUSIBLE_API_KEY')
# Replace with your actual site ID
SITE_ID = 'guides.curiousmints.com'
# Check if the API key is available
if not plausible_api_key:
raise ValueError("Plausible API key not found in the environment variables.")
# Define the Plausible API endpoint and parameters
url = "https://plausible.io/api/v1/stats/aggregate"
# Calculate the date range for the last 3 days
end_date = datetime.now().strftime('%Y-%m-%d')
start_date = (datetime.now() - timedelta(days=2)).strftime('%Y-%m-%d') # 2 days before today to include 3 days
# Parameters for the API request
params = {
'site_id': SITE_ID,
'period': 'custom',
'date': f'{start_date},{end_date}',
'metrics': 'visitors,pageviews,bounce_rate,visit_duration'
}
headers = {
'Authorization': f'Bearer {plausible_api_key}'
}
# Make the API request
response = requests.get(url, headers=headers, params=params)
# Check if the request was successful
if response.status_code == 200:
data = response.json()
print(json.dumps(data, indent=4)) # Pretty print the JSON response
else:
print(f"Error: {response.status_code} - {response.text}")
Step 4: Run the Script
Ensure you have the .env
file in the same directory as the script. Then, execute the script:
python fetch_plausible_analytics.py
Conclusion
You have successfully set up a Python script to fetch website analytics data from Plausible Analytics using the Plausible API! This guide provided a basic example to get you started. You can now expand on this by customizing the data parameters and handling different scenarios.