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.
fetch_plausible_analytics.py
Copy
import requestsimport jsonimport osfrom dotenv import load_dotenvfrom datetime import datetime, timedelta# Load environment variables from .env fileload_dotenv()# Access the API key from environment variablesplausible_api_key = os.getenv('PLAUSIBLE_API_KEY')# Replace with your actual site IDSITE_ID = 'guides.curiousmints.com'# Check if the API key is availableif not plausible_api_key: raise ValueError("Plausible API key not found in the environment variables.")# Define the Plausible API endpoint and parametersurl = "https://plausible.io/api/v1/stats/aggregate"# Calculate the date range for the last 3 daysend_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 requestparams = { '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 requestresponse = requests.get(url, headers=headers, params=params)# Check if the request was successfulif response.status_code == 200: data = response.json() print(json.dumps(data, indent=4)) # Pretty print the JSON responseelse: print(f"Error: {response.status_code} - {response.text}")
Create a Python script named fetch_plausible_analytics.py with the following content:
fetch_plausible_analytics.py
Copy
import requestsimport jsonimport osfrom dotenv import load_dotenvfrom datetime import datetime, timedelta# Load environment variables from .env fileload_dotenv()# Access the API key from environment variablesplausible_api_key = os.getenv('PLAUSIBLE_API_KEY')# Replace with your actual site IDSITE_ID = 'guides.curiousmints.com'# Check if the API key is availableif not plausible_api_key: raise ValueError("Plausible API key not found in the environment variables.")# Define the Plausible API endpoint and parametersurl = "https://plausible.io/api/v1/stats/aggregate"# Calculate the date range for the last 3 daysend_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 requestparams = { '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 requestresponse = requests.get(url, headers=headers, params=params)# Check if the request was successfulif response.status_code == 200: data = response.json() print(json.dumps(data, indent=4)) # Pretty print the JSON responseelse: print(f"Error: {response.status_code} - {response.text}")
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.