A Python client library for the Simple Analytics API
A Python wrapper for the Simple Analytics API, providing easy access to website analytics data, data exports, and account management.
Simple Analytics is a privacy-friendly analytics platform that doesn't track users or collect personal data. This library provides a Pythonic interface to their API, making it easy to:
- Retrieve aggregated website statistics
- Export raw pageview and event data
- Manage websites in your account
- Build dashboards and reports
- Python 3.12 or higher
- A Simple Analytics account (for authenticated endpoints)
Using pip:
pip install simple-analytics-pythonUsing uv:
uv add simple-analytics-pythonFrom source:
git clone https://github.com/andypiper/simple_analytics_python.git
cd simple_analytics_python
pip install -e .from simple_analytics import SimpleAnalyticsClient
# Initialize client (no auth needed for public website stats)
client = SimpleAnalyticsClient()
# Get basic stats for a public website
stats = client.stats.get(
"simpleanalytics.com",
fields=["pageviews", "visitors"]
)
print(f"Pageviews: {stats['pageviews']}")
print(f"Visitors: {stats['visitors']}")For private websites and data exports, you'll need API credentials:
import os
from simple_analytics import SimpleAnalyticsClient
client = SimpleAnalyticsClient(
api_key=os.environ.get("SA_API_KEY"),
user_id=os.environ.get("SA_USER_ID")
)Get your credentials from your Simple Analytics account settings.
Retrieve aggregated analytics data:
# Get stats with specific fields
stats = client.stats.get(
"example.com",
start="2024-01-01",
end="2024-01-31",
fields=["pageviews", "visitors", "pages", "referrers", "countries"],
limit=50
)
# Get histogram data
histogram = client.stats.get_histogram(
"example.com",
interval="day" # hour, day, week, month, year
)
# Get events
events = client.stats.get_events(
"example.com",
events=["signup", "purchase"]
)
# Apply filters
stats = client.stats.get(
"example.com",
fields=["pageviews", "pages"],
filters={
"country": "US",
"device_type": "desktop"
}
)Export raw data points (requires authentication):
from datetime import datetime, timedelta
end_date = datetime.now().strftime("%Y-%m-%d")
start_date = (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d")
# Export as JSON
data = client.export.datapoints(
"example.com",
start=start_date,
end=end_date,
fields=["added_iso", "path", "country_code", "device_type"]
)
# Export as CSV
csv_data = client.export.to_csv(
"example.com",
start=start_date,
end=end_date
)
# Export events
events = client.export.events(
"example.com",
start=start_date,
end=end_date
)Manage your Simple Analytics account (requires authentication):
# List all websites
websites = client.admin.list_websites()
# Add a new website
new_site = client.admin.add_website(
"newsite.com",
timezone="America/New_York",
public=False
)
# Get a specific website
site = client.admin.get_website("example.com")The client supports context manager usage for proper resource cleanup:
with SimpleAnalyticsClient(api_key=api_key, user_id=user_id) as client:
stats = client.stats.get("example.com", fields=["pageviews", "visitors"])
print(stats)
# Session is automatically closedThe library provides specific exceptions for different error cases:
from simple_analytics import SimpleAnalyticsClient
from simple_analytics.exceptions import (
SimpleAnalyticsError,
AuthenticationError,
RateLimitError,
NotFoundError,
ValidationError,
ServerError
)
try:
stats = client.stats.get("example.com", fields=["pageviews"])
except AuthenticationError as e:
print(f"Auth failed: {e}")
except RateLimitError as e:
print(f"Rate limited: {e}")
except NotFoundError as e:
print(f"Website not found: {e}")
except SimpleAnalyticsError as e:
print(f"API error: {e}")The main client class.
SimpleAnalyticsClient(
api_key: str | None = None,
user_id: str | None = None,
base_url: str = "https://simpleanalytics.com",
timeout: int = 30
)stats- Access to the Stats APIexport- Access to the Export APIadmin- Access to the Admin API
Get aggregated statistics for a website.
Parameters:
hostname(str): Website domainpath(str, optional): Specific page pathstart(str, optional): Start date (YYYY-MM-DD)end(str, optional): End date (YYYY-MM-DD)timezone(str, optional): Timezone for calculationsfields(list[str], optional): Fields to retrievelimit(int, optional): Max results (1-1000)info(bool, optional): Include metadata (default: True)interval(str, optional): Histogram granularityevents(str | list[str], optional): Event namesfilters(dict, optional): Filter parameters
Available fields: pageviews, visitors, histogram, pages, countries, referrers, utm_sources, utm_mediums, utm_campaigns, utm_contents, utm_terms, browser_names, os_names, device_types, seconds_on_page
Get time-series histogram data.
Get event statistics.
Export raw data points.
Parameters:
hostname(str): Website domainstart(str): Start date/timeend(str): End date/timeformat(str, optional): "json" or "csv" (default: "json")fields(list[str], optional): Fields to includetimezone(str, optional): Timezonerobots(bool, optional): Include bot traffic (default: False)data_type(str, optional): "pageviews" or "events"
Export pageview data (convenience method).
Export event data (convenience method).
Export data as CSV string.
List all websites in your account.
Add a new website.
Parameters:
hostname(str): Website domaintimezone(str, optional): Timezone (default: "UTC")public(bool, optional): Public stats (default: False)label(str, optional): Website label
Get a specific website by hostname.
The examples/ directory contains runnable examples:
| Example | Description |
|---|---|
basic_stats.py |
Basic client usage and stats retrieval |
export_data.py |
Data export examples |
histogram_chart.py |
Terminal histogram charts |
country_chart.py |
Country breakdown with emoji flags |
pages_chart.py |
Top pages visualization |
Run examples with:
# Set environment variables
export SA_API_KEY="sa_api_key_xxxx"
export SA_USER_ID="sa_user_id_xxxx"
export SA_HOSTNAME="your-website.com" # Optional
# Run with UV
uv run examples/basic_stats.py
# Or with Python
python examples/basic_stats.pyContributions are welcome! Please feel free to submit a Pull Request.
# Clone the repository
git clone https://github.com/andypiper/simple_analytics_python.git
cd simple_analytics_python
# Install development dependencies
pip install -e ".[dev]"
# Run tests
pytest tests/ -v
# Run linting
ruff check simple_analytics/# Run all tests
pytest tests/ -v
# Run with coverage (requires pytest-cov)
pytest tests/ --cov=simple_analytics --cov-report=term-missingMIT - See LICENSE file for details.
- Simple Analytics for providing a privacy-friendly analytics platform
- The Simple Analytics team for their comprehensive API documentation