Test the website's sustainability with PageSpeed
import requests
from zapier.platform.app import Zap
from zapier.platform.intent import Intent
from zapier.platform.user import User
class GooglePageSpeedInsights(Zap):
"""
Zapier integration for Google PageSpeed Insights
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.api_key = self.config.get('api_key')
if not self.api_key:
raise ValueError('Please provide a Google PageSpeed Insights API key in the Zapier app settings.')
def create(self, data):
"""
Trigger to get Google PageSpeed Insights data
"""
url = data['url']
api_url = f"https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url={url}&key={self.api_key}"
response = requests.get(api_url)
response.raise_for_status()
data = response.json()
return {
'url': url,
'desktop_score': data['lighthouseResult']['categories']['performance']['score'],
'mobile_score': data['lighthouseResult']['categories']['performance']['score'],
'desktop_recommendations': data['lighthouseResult']['audits'],
'mobile_recommendations': data['lighthouseResult']['audits'],
}
def trigger(self):
"""
Defines the trigger for this Zap
"""
return Intent(
name='Get PageSpeed Insights Data',
input_fields=[
{
'key': 'url',
'label': 'Website URL',
'required': True,
'help_text': 'Enter the URL of the website to analyze.',
},
],
perform=self.create,
)
def resource(self, **kwargs):
"""
Defines the resource for this Zap
"""
return {
'desktop_score': self.get_score('desktop'),
'mobile_score': self.get_score('mobile'),
'desktop_recommendations': self.get_recommendations('desktop'),
'mobile_recommendations': self.get_recommendations('mobile'),
}
def get_score(self, device):
"""
Helper function to retrieve the PageSpeed score for the specified device
"""
return self.data[f'{device}_score']
def get_recommendations(self, device):
"""
Helper function to retrieve the PageSpeed recommendations for the specified device
"""
return [
{
'title': audit['title'],
'description': audit['description'],
}
for audit in self.data[f'{device}_recommendations']
]
# This is the main entry point for the Zapier integration
if __name__ == '__main__':
GooglePageSpeedInsights.run()PreviousmyAIHerb Sustainability ApplicationNextZapier Integration for Website Sustainability Testing
Last updated
