Google PageSpeed Insights API for Speed Monitoring
PageSpeed Insights returns two data types: lab (Lighthouse, simulated) and field (Chrome UX Report, real users). Both important but differently. Lab shows current state right after deploy. Field shows real user experience over last 28 days. Monitoring needed for both.
Getting API Key and Basic Request
PSI API is free. Key created in Google Cloud Console → APIs & Services → Credentials. Without key limit is 400 requests/day, with key — 25,000.
import requests
from typing import Literal
PSI_API_URL = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed'
def fetch_psi(
url: str,
api_key: str,
strategy: Literal['mobile', 'desktop'] = 'mobile',
) -> dict:
params = {
'url': url,
'key': api_key,
'strategy': strategy,
'category': ['performance', 'seo', 'accessibility', 'best-practices'],
}
resp = requests.get(PSI_API_URL, params=params, timeout=60)
resp.raise_for_status()
return resp.json()
Extracting Core Web Vitals
PSI response is multi-level. Field data (CrUX) in loadingExperience, lab in lighthouseResult.audits.
Saving Results
Create PostgreSQL table for storing lab and field metrics over time:
CREATE TABLE psi_results (
id SERIAL PRIMARY KEY,
url TEXT NOT NULL,
strategy VARCHAR(10) NOT NULL,
measured_at TIMESTAMP DEFAULT NOW(),
field_lcp_ms INTEGER,
lab_performance_score NUMERIC(4,2),
lab_lcp_ms INTEGER
);
Monitoring List of Pages
For site with several priority pages (homepage, top 10 landings, checkout) run on schedule.
Alerts on Degradation
Track Lighthouse score drop and CWV transition from "good" to "needs improvement".
Important Limitations
PSI API runs Lighthouse in Google cloud, not yours. Results vary 5–15% between runs — this is normal. For reliable metrics better run 3 measurements and take median. PSI doesn't support authorized pages — for personal cabinet, cart after login use local Lighthouse via Node.js.
Running via Cron
# Crontab: daily at 6:00
0 6 * * * /usr/bin/python3 /opt/monitoring/psi_monitor.py
Results aggregated weekly — daily lab noise is high, weekly trend much informative.
Timeline
Collection script + PostgreSQL storage + email/Telegram alerts — 1–2 working days. With Grafana dashboard, pre/post deploy comparison, CI/CD pipeline integration — 3–4 days.







