### Run PageSpeed Insights with curl Source: https://developers.google.com/speed/docs/insights/v5/get-started Use this command to get a PageSpeed Insights analysis for a given URL from the command line. Replace `yourAPIKey` with your actual API key. ```bash curl https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://web.dev/&key=yourAPIKey ``` -------------------------------- ### HTTP GET Request for runPagespeed Source: https://developers.google.com/speed/docs/insights/v5/reference/pagespeedapi/runpagespeed This is the basic HTTP GET request structure for the runPagespeed method. It requires the URL of the page to analyze. ```HTTP GET https://www.googleapis.com/pagespeedonline/v5/runPagespeed ``` -------------------------------- ### Run PageSpeed Insights Source: https://developers.google.com/speed/docs/insights/v5/get-started This snippet shows how to use `curl` to call the PageSpeed Insights API v5 to get performance data for a given URL. Replace `yourAPIKey` with your actual API key. ```APIDOC ## `curl` To try out the PageSpeed Insights API from the command line: 1. Open a terminal. 2. Run the following command. Replace `yourAPIKey` with your API key. ```bash curl https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://web.dev/&key=yourAPIKey ``` The response is a JSON object. See Response to learn more about each of the properties in the response object. ``` -------------------------------- ### PageSpeed Insights API Response Structure Source: https://developers.google.com/speed/docs/insights/v5/get-started The API returns a JSON object containing various performance metrics and analysis results. This example shows a partial structure including loading experience and Lighthouse audit data. ```json { "captchaResult": "CAPTCHA_NOT_NEEDED", "kind": "pagespeedonline#result", "id": "https://developers.google.com/", "loadingExperience": { "id": "https://developers.google.com/", "metrics": { "FIRST_CONTENTFUL_PAINT_MS": { "percentile": 3482, "distributions": [ { "min": 0, "max": 1000, "proportion": 0.37151728768042963 }, { "min": 1000, "max": 2500, "proportion": 0.4244153519077991 }, { "min": 2500, "proportion": 0.2040673604117713 } ], "category": "SLOW" }, "FIRST_INPUT_DELAY_MS": { "percentile": 36, "distributions": [ { "min": 0, "max": 50, "proportion": 0.960628961482204 }, { "min": 50, "max": 250, "proportion": 0.02888834714773281 }, { "min": 250, "proportion": 0.010482691370063388 } ], "category": "FAST" } }, "overall_category": "SLOW", "initial_url": "https://developers.google.com/" }, "originLoadingExperience": { "id": "https://developers.google.com", "metrics": { "FIRST_CONTENTFUL_PAINT_MS": { "percentile": 2761, "distributions": [ { "min": 0, "max": 1000, "proportion": 0.4236433226493666 }, { "min": 1000, "max": 2500, "proportion": 0.45045120795679117 }, { "min": 2500, "proportion": 0.1259054693938423 } ], "category": "SLOW" }, "FIRST_INPUT_DELAY_MS": { "percentile": 45, "distributions": [ { "min": 0, "max": 50, "proportion": 0.9537371485251699 }, { "min": 50, "max": 250, "proportion": 0.03044972719889055 }, { "min": 250, "proportion": 0.01581312427593959 } ], "category": "FAST" } }, "overall_category": "SLOW", "initial_url": "https://developers.google.com/" }, "lighthouseResult": { "requestedUrl": "https://developers.google.com/", "finalUrl": "https://developers.google.com/", "lighthouseVersion": "3.2.0", "userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/72.0.3584.0 Safari/537.36", "fetchTime": "2018-11-01T03:03:58.394Z", "environment": { "networkUserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3559.0 Safari/537.36", "hostUserAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/72.0.3584.0 Safari/537.36", "benchmarkIndex": 590.0 }, "runWarnings": [], "configSettings": { "emulatedFormFactor": "desktop", "locale": "en-US", "onlyCategories": [ "performance" ] }, "audits": { "estimated-input-latency": { "id": "estimated-input-latency", "title": "Estimated Input Latency", "description": "The score above is an estimate of how long your app takes to respond to user input, in milliseconds, during the busiest 5s window of page load. If your latency is higher than 50 ms, users may perceive your app as laggy. [Learn more](https://developers.google.com/web/tools/lighthouse/audits/estimated-input-latency).", "score": 1.0, "scoreDisplayMode": "numeric", "displayValue": "30\u00a0ms" }, "uses-rel-preconnect": { "id": "uses-rel-preconnect", "title": "Preconnect to required origins", "description": "Consider adding preconnect or dns-prefetch resource hints to establish early connections to important third-party origins. [Learn more](https://developers.google.com/web/fundamentals/performance/resource-prioritization#preconnect).", "score": 1.0, "scoreDisplayMode": "numeric", "details": { "headings": [], "type": "opportunity", "items": [], "overallSavingsMs": 0.0 } } }, "categories": { "performance": { "id": "performance", "title": "Performance", "score": 0.96, "auditRefs": [ { "id": "first-contentful-paint", "weight": 3.0, "group": "metrics" }, { "id": "first-meaningful-paint", "weight": 1.0, "group": "metrics" } ] } }, "categoryGroups": { "a11y-element-names": { "title": "Elements Have Discernible Names", "description": "These are opportunities to improve the semantics of the controls in your application. This may enhance the experience for users of assistive technology, like a screen reader." }, "a11y-language": { "title": "Page Specifies Valid Language" } } } } ``` -------------------------------- ### runPagespeed Source: https://developers.google.com/speed/docs/insights/v5/reference/pagespeedapi/runpagespeed Runs PageSpeed analysis on the page at the specified URL, and returns PageSpeed scores, a list of suggestions to make that page faster, and other information. ```APIDOC ## GET https://www.googleapis.com/pagespeedonline/v5/runPagespeed ### Description Runs PageSpeed analysis on the page at the specified URL, and returns PageSpeed scores, a list of suggestions to make that page faster, and other information. ### Method GET ### Endpoint https://www.googleapis.com/pagespeedonline/v5/runPagespeed ### Parameters #### Query Parameters - **url** (string) - Required - The URL to fetch and analyze - **category** (string) - Optional - A Lighthouse category to run; if none are given, only Performance category will be run. Acceptable values: `accessibility`, `best-practices`, `performance`, `seo` - **locale** (string) - Optional - The locale used to localize formatted results - **strategy** (string) - Optional - The analysis strategy (desktop or mobile) to use, and desktop is the default. Acceptable values: `desktop`, `mobile` - **utm_campaign** (string) - Optional - Campaign name for analytics. - **utm_source** (string) - Optional - Campaign source for analytics. ### Request Body Do not supply a request body with this method. ### Response #### Success Response (200) - **id** (string) - The unique ID of this PageSpeed Insights run. - **kind** (string) - This is a V5 API. - **loadingExperience** (object) - Relevant times in millisecondsElapsing during the loading of the page. - **originLoadingExperience** (object) - Relevant times in millisecondsElapsing during the loading of the page. - **psiPageUrl** (string) - The URL of the page that was analyzed. - **responseCode** (integer) - The HTTP response code of the original request. - **ruleGroups** (object) - The Structure of the response is a JSON object, as returned by the server. - **lighthouseResult** (object) - The Structure of the response is a JSON object, as returned by the server. - **analysisId** (string) - The unique ID of this PageSpeed Insights run. - **captchaResult** (string) - The Structure of the response is a JSON object, as returned by the server. - **error** (object) - The Structure of the response is a JSON object, as returned by the server. - **kind** (string) - This is a V5 API. - **id** (string) - The unique ID of this PageSpeed Insights run. - **loadingExperience** (object) - Relevant times in millisecondsElapsing during the loading of the page. - **originLoadingExperience** (object) - Relevant times in millisecondsElapsing during the loading of the page. - **psiPageUrl** (string) - The URL of the page that was analyzed. - **responseCode** (integer) - The HTTP response code of the original request. - **ruleGroups** (object) - The Structure of the response is a JSON object, as returned by the server. - **lighthouseResult** (object) - The Structure of the response is a JSON object, as returned by the server. - **analysisId** (string) - The unique ID of this PageSpeed Insights run. - **captchaResult** (string) - The Structure of the response is a JSON object, as returned by the server. - **error** (object) - The Structure of the response is a JSON object, as returned by the server. ### Response Example { "example": "{\n \"lighthouseResult\": {\n \"audits\": {\n \"metrics.timing.interactive\": {\n \"id\": \"metrics.timing.interactive\",\n \"title\": \"Time to interactive\",\n \"score\": 1,\n \"numericValue\": 1313.304,\n \"source\": {\n \"id\": \"metrics.timing.interactive\"\n }\n },\n \"metrics.timing.total-blocking\": {\n \"id\": \"metrics.timing.total-blocking\",\n \"title\": \"Total blocking time\",\n \"score\": 1,\n \"numericValue\": 0,\n \"source\": {\n \"id\": \"metrics.timing.total-blocking\"\n }\n },\n \"metrics.performance.first-contentful-paint\": {\n \"id\": \"metrics.performance.first-contentful-paint\",\n \"title\": \"First contentful paint\",\n \"score\": 1,\n \"numericValue\": 1000.0,\n \"source\": {\n \"id\": \"metrics.performance.first-contentful-paint\"\n }\n }\n },\n \"categories\": {\n \"performance\": {\n \"id\": \"performance\",\n \"title\": \"Performance\",\n \"score\": 1\n }\n }\n },\n \"loadingExperience\": {\n \"metrics\": {\n \"FIRST_CONTENTFUL_PAINT_MS\": {\n \"avg\": 1000.0,\n \"percentiles\": {\n \"50\": 1000.0\n }\n },\n \"INTERACTIVE_MS\": {\n \"avg\": 1313.304,\n \"percentiles\": {\n \"50\": 1313.304\n }\n },\n \"TOTAL_BLOCKING_TIME_MS\": {\n \"avg\": 0.0,\n \"percentiles\": {\n \"50\": 0.0\n }\n }\n },\n \"overall_experience\": \"GOOD\"\n }\n}" } ``` -------------------------------- ### RunPageSpeed Source: https://developers.google.com/speed/docs/insights/v5/reference/pagespeedapi/runpagespeed Analyzes the content of a web page and returns a score, and suggestions to make that page faster. ```APIDOC ## GET runPagespeed ### Description Analyzes the content of a web page and generates a score, and suggestions to make that page faster. ### Method GET ### Endpoint /runPagespeed ### Parameters #### Query Parameters - **url** (string) - Required - The URL to investigate. - **filter_third_party_resources** (boolean) - Optional - Related to third party strings. - **locale** (string) - Optional - The locale used to calculate the score. - **rule** (enum) - Optional - A PageSpeed rule to run; if present, only the results for that rule will be returned. Acceptable values for **rule** are: * `ACCESSIBILITY` * `BEST_PRACTICES` * `SEO` * `SPEED` * `PWA` ### Response #### Success Response (200) - **captchaResult** (string) - The captcha verify result. Acceptable values: `CAPTCHA_BLOCKING`, `CAPTCHA_MATCHED`, `CAPTCHA_NEEDED`, `CAPTCHA_NOT_NEEDED`, `CAPTCHA_UNMATCHED`. - **kind** (string) - Kind of result. - **id** (string) - Canonicalized and final URL for the document, after following page redirects (if any). - **loadingExperience** (object) - Metrics of end users' page loading experience. - **originLoadingExperience** (object) - Metrics of the origin loading experience. - **lighthouseResult** (object) - The Structure of the Lighthouse object. - **analysisUTCTimestamp** (string) - The timestamp of this analysis. - **version** (object) - The version of PageSpeed used to generate these results. #### Response Example { "captchaResult": "CAPTCHA_NOT_NEEDED", "kind": "pagespeedonline#result", "id": "https://example.com/", "loadingExperience": { "id": "https://example.com/", "metrics": { "FIRST_INPUT_DELAY": { "percentile": 75, "distributions": [ { "min": 0, "max": 100, "proportion": 0.5 } ], "category": "FAST" } }, "overall_category": "FAST", "initial_url": "https://example.com/" }, "originLoadingExperience": { "id": "https://example.com/", "metrics": { "FIRST_INPUT_DELAY": { "percentile": 75, "distributions": [ { "min": 0, "max": 100, "proportion": 0.5 } ], "category": "FAST" } }, "overall_category": "FAST", "initial_url": "https://example.com/" }, "lighthouseResult": { "requestedUrl": "https://example.com/", "finalUrl": "https://example.com/", "lighthouseVersion": "10.0.0", "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36", "fetchTime": "2023-10-27T10:00:00.000Z", "environment": { "networkUserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36", "hostUserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36", "benchmarkIndex": 1000 }, "runWarnings": [], "configSettings": { "emulatedFormFactor": "desktop", "locale": "en-US" }, "audits": {}, "categories": {}, "categoryGroups": {}, "runtimeError": null, "timing": { "total": 5000 }, "i18n": { "rendererFormattedStrings": {} } }, "analysisUTCTimestamp": "2023-10-27T10:00:00.000Z", "version": { "major": 5, "minor": 0 } } ``` -------------------------------- ### PageSpeed Insights v5 Response Structure Source: https://developers.google.com/speed/docs/insights/v5/reference/pagespeedapi/runpagespeed This section details the structure of the response object returned by the PageSpeed Insights API v5. It includes information about origin loading experience, Lighthouse results, and various metrics and audits. ```APIDOC ## PageSpeed Insights v5 Response ### Description This describes the structure of the response object from the PageSpeed Insights API v5. ### Response Body - **originLoadingExperience** (object) - Metrics of the aggregated page loading experience of the origin. - **id** (string) - The url, pattern or origin which the metrics are on. - **metrics** (object) - - **(key)** (object) - The type of the metric. - **percentile** (integer) - - **distributions** (list) - - **min** (integer) - - **max** (integer) - - **proportion** (double) - - **category** (string) - Acceptable values: "AVERAGE", "FAST", "NONE", "SLOW" - **overall_category** (string) - Acceptable values: "AVERAGE", "FAST", "NONE", "SLOW" - **initial_url** (string) - - **analysisUTCTimestamp** (string) - The UTC timestamp of this analysis. - **lighthouseResult** (object) - Lighthouse response for the audit url as an object. - **requestedUrl** (string) - The original requested url. - **finalUrl** (string) - The final resolved url that was audited. - **lighthouseVersion** (string) - The lighthouse version that was used to generate this LHR. - **userAgent** (string) - The user agent that was used to run this LHR. - **fetchTime** (string) - The time that this run was fetched. - **environment** (object) - Environment settings that were used when making this LHR. - **networkUserAgent** (string) - - **hostUserAgent** (string) - - **benchmarkIndex** (double) - - **runWarnings** (list) - List of all run warnings in the LHR. Will always output to at least `[]`. - **configSettings** (object) - The configuration settings for this LHR. - **emulatedFormFactor** (string) - The form factor the emulation should use. Acceptable values: "UNKNOWN_FORM_FACTOR", "desktop", "mobile", "none" - **locale** (string) - The locale setting - **onlyCategories** (object) - - **audits** (object) - Map of audits in the LHR. - **(key)** (object) - - **id** (string) - The audit's id. - **title** (string) - The human readable title. - **description** (string) - The description of the audit. - **score** (object) - - **scoreDisplayMode** (string) - The enumerated score display mode. Acceptable values: "SCORE_DISPLAY_MODE_UNSPECIFIED", "binary", "error", "informative", "manual", "not_applicable", "numeric" - **displayValue** (string) - The value that should be displayed on the UI for this audit. - **explanation** (string) - An explanation of the errors in the audit. - **errorMessage** (string) - An error message from a thrown error inside the audit. - **warnings** (object) - - **details** (object) - Freeform details section of the audit. - **(key)** (any value) - - **categories** (object) - Map of categories in the LHR. - **(key)** (object) - - **id** (string) - The string identifier of the category. - **title** (string) - The human-friendly name of the category - **description** (string) - A more detailed description of the category and its importance. - **score** (object) - - **manualDescription** (string) - A description for the manual audits in the category. - **auditRefs** (list) - An array of references to all the audit members of this category. - **id** (string) - The audit ref id. - **weight** (double) - The weight this audit's score has on the overall category score. ``` -------------------------------- ### Fetch and Display PageSpeed Insights Data with JavaScript Source: https://developers.google.com/speed/docs/insights/v5/get-started This code snippet uses the PageSpeed Insights API v5 to measure the performance of a target URL and displays the results in the browser. It requires the fetch API, which is available in modern browsers. ```javascript /** * Fetches and displays PageSpeed Insights data. */ async function run() { const apiEndpoint = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed'; const targetUrl = 'https://web.dev/'; const url = new URL(apiEndpoint); url.searchParams.set('url', targetUrl); try { const response = await fetch(url); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const json = await response.json(); // See // https://developers.google.com/speed/docs/insights/v5/reference/pagespeedapi/runpagespeed#response // to learn more about each of the properties in the response object. showInitialContent(json.id); const cruxMetrics = { 'First Contentful Paint': json.loadingExperience.metrics.FIRST_CONTENTFUL_PAINT_MS?.category, 'Interaction to Next Paint': json.loadingExperience.metrics.INTERACTION_TO_NEXT_PAINT?.category, }; showCruxContent(cruxMetrics); const lighthouse = json.lighthouseResult; const lighthouseMetrics = { 'First Contentful Paint': lighthouse.audits['first-contentful-paint']?.displayValue, 'Speed Index': lighthouse.audits['speed-index']?.displayValue, 'Largest Contentful Paint': lighthouse.audits['largest-contentful-paint']?.displayValue, 'Total Blocking Time': lighthouse.audits['total-blocking-time']?.displayValue, 'Time To Interactive': lighthouse.audits['interactive']?.displayValue, }; showLighthouseContent(lighthouseMetrics); } catch (error) { console.error('Fetching PageSpeed Insights failed:', error); document.body.textContent = `Failed to fetch PageSpeed data. Check the console for errors.`; } } /** * Displays initial content, including the page ID. * @param {string} id The ID of the page being tested. */ function showInitialContent(id) { document.body.innerHTML = ''; // Clear previous content const title = document.createElement('h1'); title.textContent = 'PageSpeed Insights API Demo'; document.body.appendChild(title); const page = document.createElement('p'); page.textContent = `Page tested: ${id}`; document.body.appendChild(page); } /** * Displays CrUX metrics. * @param {!Object} cruxMetrics The CrUX metrics to display. */ function showCruxContent(cruxMetrics) { const cruxHeader = document.createElement('h2'); cruxHeader.textContent = 'Chrome User Experience Report Results'; document.body.appendChild(cruxHeader); for (const key in cruxMetrics) { const p = document.createElement('p'); p.textContent = `${key}: ${cruxMetrics[key]}`; document.body.appendChild(p); } } /** * Displays Lighthouse metrics. * @param {!Object} lighthouseMetrics The Lighthouse metrics to display. */ function showLighthouseContent(lighthouseMetrics) { const lighthouseHeader = document.createElement('h2'); lighthouseHeader.textContent = 'Lighthouse Results'; document.body.appendChild(lighthouseHeader); for (const key in lighthouseMetrics) { const p = document.createElement('p'); p.textContent = `${key}: ${lighthouseMetrics[key]}`; document.body.appendChild(p); } } run(); ``` -------------------------------- ### PageSpeed Insights API v5 Response Structure Source: https://developers.google.com/speed/docs/insights/v5/reference/pagespeedapi/runpagespeed This JSON structure represents a successful response from the PageSpeed Insights API v5, detailing various metrics and results. ```json { "captchaResult": string, "kind": "pagespeedonline#result", "id": string, "loadingExperience": { "id": string, "metrics": { (key): { "percentile": integer, "distributions": [ { "min": integer, "max": integer, "proportion": double } ], "category": string } }, "overall_category": string, "initial_url": string }, "originLoadingExperience": { "id": string, "metrics": { (key): { "percentile": integer, "distributions": [ { "min": integer, "max": integer, "proportion": double } ], "category": string } }, "overall_category": string, "initial_url": string }, "lighthouseResult": { "requestedUrl": string, "finalUrl": string, "lighthouseVersion": string, "userAgent": string, "fetchTime": string, "environment": { "networkUserAgent": string, "hostUserAgent": string, "benchmarkIndex": double }, "runWarnings": [ (value) ], "configSettings": { "emulatedFormFactor": string, "locale": string, "onlyCategories": (value), "onlyCategories": (value) }, "audits": { (key): { "id": string, "title": string, "description": string, "score": (value), "score": (value), "scoreDisplayMode": string, "displayValue": string, "explanation": string, "errorMessage": string, "warnings": (value), "warnings": (value), "details": { (key): (value) } } }, "categories": { (key): { "id": string, "title": string, "description": string, "score": (value), "score": (value), "manualDescription": string, "auditRefs": [ { "id": string, "weight": double, "group": string } ] } }, "categoryGroups": { (key): { "title": string, "description": string } }, "runtimeError": { "code": string, "message": string }, "timing": { "total": double }, "i18n": { "rendererFormattedStrings": { "varianceDisclaimer": string, "opportunityResourceColumnLabel": string, "opportunitySavingsColumnLabel": string, "errorMissingAuditInfo": string, "errorLabel": string, "warningHeader": string, "auditGroupExpandTooltip": string, "passedAuditsGroupTitle": string, "notApplicableAuditsGroupTitle": string, "manualAuditsGroupTitle": string, "toplevelWarningsMessage": string, "scorescaleLabel": string, "crcLongestDurationLabel": string, "crcInitialNavigation": string, "lsPerformanceCategoryDescription": string, "labDataTitle": string } } }, "analysisUTCTimestamp": string, "version": { "major": integer, "minor": integer } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.