Skip to content

Instantly share code, notes, and snippets.

@nicogaspa
Last active May 15, 2021 09:52
Show Gist options
  • Save nicogaspa/4f4c366567a9b01c9612a697e6d081e1 to your computer and use it in GitHub Desktop.
Save nicogaspa/4f4c366567a9b01c9612a697e6d081e1 to your computer and use it in GitHub Desktop.
Google PageSpeed API class
import requests
API_KEY = "" # TODO
VERSION = "v5"
class GooglePageSpeedService:
def __init__(self):
self.api_key = API_KEY
self.base_url = (
f"https://pagespeedonline.googleapis.com/pagespeedonline/{VERSION}"
)
def get_insights(
self, url: str, strategy: str = None, category: str = None, locale: str = None
):
"""
:param url: The URL to fetch and analyze
:param strategy: DESKTOP, MOBILE
:param category: ACCESSIBILITY, BEST_PRACTICES, PERFORMANCE, PWA, SEO
:param locale: The locale used to localize formatted results
:return:
"""
params = {
"url": url,
"api_key": self.api_key
}
if strategy is not None:
params["strategy"] = strategy
if category is not None:
params["category"] = category
if locale is not None:
params["locale"] = locale
result = requests.get(self.base_url, params=params)
return result.json()
if __name__ == "__main__":
service = GooglePageSpeedService()
results = service.get_insights("https://www.nytimes.com")
results = service.get_insights("https://www.nytimes.com", category="ACCESSIBILITY")
results = service.get_insights("https://www.nytimes.com", category="BEST_PRACTICES")
results = service.get_insights("https://www.nytimes.com", category="PWA")
results = service.get_insights("https://www.nytimes.com", category="SEO")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment