Hide

Developer's Guide (v1): Getting Started

This document explains how to get started using the PageSpeed Insights API.

Contents

  1. Introduction
  2. Before you start
    1. Get familiar with PageSpeed
    2. Get a Google Account
    3. Learn how to identify your application to Google
  3. PageSpeed Insights API background
  4. Invoking the API
    1. Standard query parameters
    2. PageSpeed Insights-specific query parameters
  5. Example API calls
    1. From the command line
    2. From JavaScript
  6. Demo Video

Introduction

This document is intended for developers who want to write applications that can interact with the PageSpeed Insights API.

PageSpeed Insights is a tool that helps developers optimize their web pages by analyzing the pages and generating tailored suggestions to make the pages faster. You can use the PageSpeed Insights API to programmatically generate PageSpeed scores and suggestions.

Before you start

Get a Google Account

You need to have a Google Account so you can get an API key to identify your application to Google. (See below.)

Get familiar with PageSpeed

If you're unfamiliar with PageSpeed, see the PageSpeed Web Performance Best Practices.

Learn how to identify your application to Google

Your application needs to identify itself every time it sends a request to the PageSpeed Insights API, by including an API key with each request.

Acquiring and using an API key

To acquire an API key:

  1. Go to the Google Developers Console.
  2. Select a project, or create a new one.
  3. In the sidebar on the left, expand APIs & auth. Next, click APIs. Select the Enabled APIs link in the API section to see a list of all your enabled APIs. Make sure that the PageSpeed Insights API is on the list of enabled APIs. If you have not enabled it, select the API from the list of APIs, then select the Enable API button for the API.
  4. In the sidebar on the left, select Credentials.
  5. This API supports two types of credentials. Create whichever credentials are appropriate for your project:
    • OAuth: Your application must send an OAuth 2.0 token with any request that accesses private user data. Your application sends a client ID and, possibly, a client secret to obtain a token. You can generate OAuth 2.0 credentials for web applications, service accounts, or installed applications.

      To create an OAuth 2.0 token, click Create new Client ID, provide the required information where requested, and click Create Client ID.

      You can generate OAuth 2.0 credentials for web applications, service accounts, or installed applications.

      Web applications

      A web application is accessed by web browsers over a network.

      • Applications that use JavaScript to access the PageSpeed Insights API must specify authorized JavaScript origins. The origins identify the domains from which your application can send API requests.
      • Applications that use languages and frameworks like PHP, Java, Python, Ruby, and .NET must specify authorized redirect URIs. The redirect URIs are the endpoints to which the OAuth 2.0 server can send responses.

      Service accounts

      A service account is used in an application that calls APIs on behalf of an application that does not access user information. This type of application needs to prove its own identity, but it does not need a user to authorize requests. The Google Accounts documentation contains more details about service accounts.

      Installed applications

      An installed application runs on a desktop computer or handheld device. You can create OAuth 2.0 credentials for Android, Chrome, iOS, and other installed applications.

      Android

      You need to specify your Android app's package name and SHA1 fingerprint.

      1. In the Package name field, enter your Android app's package name.
      2. In a terminal, run the Keytool utility to get the SHA1 fingerprint for your digitally signed .apk file's public certificate.
        keytool -exportcert -alias androiddebugkey -keystore path-to-debug-or-production-keystore -list -v

        The Keytool prints the fingerprint to the shell. For example:

        $ keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v
        Enter keystore password: Type "android" if using debug.keystore
        Alias name: androiddebugkey
        Creation date: Aug 27, 2012
        Entry type: PrivateKeyEntry
        Certificate chain length: 1
        Certificate[1]:
        Owner: CN=Android Debug, O=Android, C=US
        Issuer: CN=Android Debug, O=Android, C=US
        Serial number: 503bd581
        Valid from: Mon Aug 27 13:16:01 PDT 2012 until: Wed Aug 20 13:16:01 PDT 2042
        Certificate fingerprints:
           MD5:  1B:2B:2D:37:E1:CE:06:8B:A0:F0:73:05:3C:A3:63:DD
           SHA1: D8:AA:43:97:59:EE:C5:95:26:6A:07:EE:1C:37:8E:F4:F0:C8:05:C8
           SHA256: F3:6F:98:51:9A:DF:C3:15:4E:48:4B:0F:91:E3:3C:6A:A0:97:DC:0A:3F:B2:D2:E1:FE:23:57:F5:EB:AC:13:30
           Signature algorithm name: SHA1withRSA
           Version: 3

        Copy the SHA1 fingerprint, which is highlighted in the example above.

      3. Paste the SHA1 fingerprint into the form where requested.
      4. Click Create Client ID.

      Chrome application

      You need to specify the Application ID for your Chrome app or extension. Use the Google Chrome Identity API to obtain that ID.

    • iOS

      You need to specify the app's Bundle ID and App Store ID.

      • The application's Bundle ID is the bundle identifier as listed in the app's .plist file. For example: com.example.myapp.
      • The application's App Store ID is in the app's iTunes URL so long as the app was published in the Apple iTunes App Store. For example, in the app URL http://itunes.apple.com/us/app/google+/id447119634, the App Store ID is 447119634.

      Other

      The Developers Console does not require any additional information to create OAuth 2.0 credentials for other types of installed applications.

    • Public API access: A request that does not provide an OAuth 2.0 token must send an API key. The key identifies your project and provides API access, quota, and reports.

      The API supports several types of API keys. If the key type that you need does not already exist, create an API key by selecting Create New Key and then selecting the appropriate key type. Then enter the additional data for that key type and click Create.

      Server keys

      Create and use a server key if your application runs on a server. Do not use this key outside of your server code. For example, do not embed it in a web page. To prevent quota theft, restrict your key so that requests are only allowed from your servers' source IP addresses.

      Browser keys

      Create and use a browser key if your application runs on a client, such as a web browser. To prevent your key from being used on unauthorized sites, only allow referrals from domains you administer.

      iOS keys

      Create and use an iOS key if your application runs on iOS devices. Google verifies that each request originates from an iOS application that matches one of the bundle identifiers you specify. An app's .plist file contains its bundle identifier. Example: com.example.MyApp

      Android keys

      Create and use an Android key if your application runs on Android devices. To do so, you need to specify the SHA1 fingerprints and package names of the application using that key.

      1. In a terminal, run the Keytool utility to get the SHA1 fingerprint for your digitally signed .apk file's public certificate.
        keytool -exportcert -alias androiddebugkey -keystore path-to-debug-or-production-keystore -list -v

        The Keytool prints the fingerprint to the shell. For example:

        $ keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore -list -v
        Enter keystore password: Type "android" if using debug.keystore
        Alias name: androiddebugkey
        Creation date: Aug 27, 2012
        Entry type: PrivateKeyEntry
        Certificate chain length: 1
        Certificate[1]:
        Owner: CN=Android Debug, O=Android, C=US
        Issuer: CN=Android Debug, O=Android, C=US
        Serial number: 503bd581
        Valid from: Mon Aug 27 13:16:01 PDT 2012 until: Wed Aug 20 13:16:01 PDT 2042
        Certificate fingerprints:
           MD5:  1B:2B:2D:37:E1:CE:06:8B:A0:F0:73:05:3C:A3:63:DD
           SHA1: D8:AA:43:97:59:EE:C5:95:26:6A:07:EE:1C:37:8E:F4:F0:C8:05:C8
           SHA256: F3:6F:98:51:9A:DF:C3:15:4E:48:4B:0F:91:E3:3C:6A:A0:97:DC:0A:3F:B2:D2:E1:FE:23:57:F5:EB:AC:13:30
           Signature algorithm name: SHA1withRSA
           Version: 3

        Copy the SHA1 fingerprint, which is highlighted in the example above.

      2. Paste the SHA1 fingerprint into the form where requested.
      3. After the fingerprint, type a semicolon and then enter your Android app's package name.
      4. Click Create.

To keep your API keys secure, follow the best practices for securely using API keys.

After you have an API key, your application can append the query parameter key=yourAPIKey to all request URLs.

The API key is safe for embedding in URLs; it doesn't need any encoding.

PageSpeed Insights API background

The results returned by the PageSpeed Insights API include the following types of information:

Score
The PageSpeed Score (0-100) indicates how much faster a page could be. A high score indicates little room for improvement, while a low score indicates more room for improvement.
Rule
PageSpeed analyzes web pages using rules. Each PageSpeed rule is based on general principles of web page performance, such as resource caching, data upload and download size, and client-server round-trip times. PageSpeed rules generate rule results and rule impacts, described below.
Rule Result
A rule result is a suggestion generated by a rule that, if implemented, would make the page faster and increase the PageSpeed score for that page. For instance, if a compressible resource is served uncompressed, the PageSpeed Enable Compression rule would generate a result that recommends that the developer enable compression for that resource.
Rule Impact
Each PageSpeed rule generates an impact number (an unbounded floating point value) that indicates the importance or priority of implementing the rule-result suggestions for the rule, relative to other rules. For instance, if enabling compression would save 1MB, while optimizing images would save 500kB, the Enable Compression rule would have an impact value that is twice that of the Optimize Images rule. An impact of zero indicates that there are no suggestions for improvement for that rule.

Invoking the API

To invoke the API, call the runPagespeed method, specifying the URL, API key, and other parameters in the query string. The following tables summarize the available parameters.

Standard query parameters

All parameters are optional except where noted.

Parameter Meaning Notes
callback Callback function.
  • Name of the JavaScript callback function that handles the response.
  • Used in JavaScript JSON-P requests.
key

API key. (REQUIRED)

  • Your API key identifies your project and provides you with API access, quota, and reports.
  • Obtain your project's API key from the APIs console.
prettyprint

Returns response with identations and line breaks.

  • Returns the response in a human-readable format if true.
  • Default value: true.
  • When this is false, it can reduce the response payload size, which might lead to better performance in some environments.
userIp IP address of the site where the request originates.

PageSpeed Insights-specific query parameters

Parameter Meaning Default
url The URL of the page for which the PageSpeed Insights API should generate results. N/A (REQUIRED)
locale The locale that results should be generated in. See the list of supported locales. If the specified locale is not supported, the default locale is used. en_US
strategy The strategy to use when analyzing the page. Valid values are desktop and mobile. desktop
rule The PageSpeed rules to run. Can be specified multiple times (for example, &rule=AvoidBadRequests&rule=MinifyJavaScript) to request multiple rules. If unspecified, all rules for the current strategy are used. Most users of the API should not need to specify this parameter. all rules for the current strategy

Example API calls

From the command line

You can invoke the PageSpeed Insights API from the Linux/UNIX command line, using a program such as curl.

The following example uses this approach to fetch PageSpeed results for the URL http://code.google.com/speed/page-speed/. The PageSpeed score, page statistics, and PageSpeed formatted results are returned in the JSON data format.

Formatted results are keyed by rule identifiers (such as AvoidBadRequests or MinifyJavaScript), and contain the score and impact for that rule, as well as suggestions generated by the rule that, if implemented, will make the page load faster. To learn more about the fields in the JSON response, see the PageSpeed Insights API Reference document.

Request:

$ curl "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=http://code.google.com/speed/page-speed/&key=yourAPIKey"

Response:

{
 "kind": "pagespeedonline#result",
 "id": "/speed/pagespeed",
 "responseCode": 200,
 "title": "PageSpeed Home",
 "score": 90,
 "pageStats": {
  "numberResources": 22,
  "numberHosts": 7,
  "totalRequestBytes": "2761",
  "numberStaticResources": 16,
  "htmlResponseBytes": "91981",
  "cssResponseBytes": "37728",
  "imageResponseBytes": "13909",
  "javascriptResponseBytes": "247214",
  "otherResponseBytes": "8804",
  "numberJsResources": 6,
  "numberCssResources": 2
 },
 "formattedResults": {
  "locale": "en_US",
  "ruleResults": {
   "AvoidBadRequests": {
    "localizedRuleName": "Avoid bad requests",
    "ruleImpact": 0.0
   },
   ...
   "MinifyJavaScript": {
    "localizedRuleName": "Minify JavaScript",
    "ruleImpact": 0.1417,
    "urlBlocks": [
     {
      "header": {
       "format": "Minifying the following JavaScript resources could reduce their size by $1 ($2% reduction).",
       "args": [
        {
         "type": "BYTES",
         "value": "1.3KiB"
        },
        {
         "type": "INT_LITERAL",
         "value": "0"
        }
       ]
      },
      "urls": [
       {
        "result": {
         "format": "Minifying $1 could save $2 ($3% reduction).",
         "args": [
          {
           "type": "URL",
           "value": "http://code.google.com/js/codesite_tail.pack.04102009.js"
          },
          {
           "type": "BYTES",
           "value": "717B"
          },
          {
           "type": "INT_LITERAL",
           "value": "1"
          }
         ]
        }
       },
       ...
       {
        "result": {
         "format": "Minifying $1 could save $2 ($3% reduction).",
         "args": [
          {
           "type": "URL",
           "value": "http://www.gmodules.com/ig/proxy?url\u003dhttp%3A%2F%2Fjqueryjs.googlecode.com%2Ffiles%2Fjquery-1.2.6.min.js"
          },
          {
           "type": "BYTES",
           "value": "258B"
          },
          {
           "type": "INT_LITERAL",
           "value": "0"
          }
         ]
        }
       }
      ]
     }
    ]
   },
   ...
   "SpriteImages": {
    "localizedRuleName": "Combine images into CSS sprites",
    "ruleImpact": 0.0
   }
  }
 },
 "version": {
  "major": 1,
  "minor": 11
 }
}

From JavaScript

You can invoke the PageSpeed Insights API from JavaScript in the browser, using the callback query parameter and a callback function to generate JSON-P results. This allows you to write rich applications that display PageSpeed data without writing any server-side code.

The following example uses this approach to display PageSpeed results and other information for the URL http://code.google.com/speed/page-speed/. This example also makes use of the Google Chart Tools to visualize the information generated by the PageSpeed Insights API.

First, specify your Google API key (learn more about API keys):

<script>
// Specify your actual API key here:
var API_KEY = 'yourAPIKey';

// Specify the URL you want PageSpeed results for here:
var URL_TO_GET_RESULTS_FOR = 'http://code.google.com/speed/page-speed/';
</script>

Next, fetch PageSpeed Results from the PageSpeed Insights API:

<script>
var API_URL = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?';
var CHART_API_URL = 'http://chart.apis.google.com/chart?';

// Object that will hold the callbacks that process results from the
// PageSpeed Insights API.
var callbacks = {}

// Invokes the PageSpeed Insights API. The response will contain
// JavaScript that invokes our callback with the PageSpeed results.
function runPagespeed() {
  var s = document.createElement('script');
  s.type = 'text/javascript';
  s.async = true;
  var query = [
    'url=' + URL_TO_GET_RESULTS_FOR,
    'callback=runPagespeedCallbacks',
    'key=' + API_KEY,
  ].join('&');
  s.src = API_URL + query;
  document.head.insertBefore(s, null);
}

// Our JSONP callback. Checks for errors, then invokes our callback handlers.
function runPagespeedCallbacks(result) {
  if (result.error) {
    var errors = result.error.errors;
    for (var i = 0, len = errors.length; i < len; ++i) {
      if (errors[i].reason == 'badRequest' && API_KEY == 'yourAPIKey') {
        alert('Please specify your Google API key in the API_KEY variable.');
      } else {
        // NOTE: your real production app should use a better
        // mechanism than alert() to communicate the error to the user.
        alert(errors[i].message);
      }
    }
    return;
  }

  // Dispatch to each function on the callbacks object.
  for (var fn in callbacks) {
    var f = callbacks[fn];
    if (typeof f == 'function') {
      callbacks[fn](result);
    }
  }
}

// Invoke the callback that fetches results. Async here so we're sure
// to discover any callbacks registered below, but this can be
// synchronous in your code.
setTimeout(runPagespeed, 0);
</script>

Using the code above to fetch results from the PageSpeed Insights API, we're now ready to display interesting information in the user's browser using the examples below.

Example 1: Display the PageSpeed score as a Google-O-Meter

This example displays a Google-O-Meter that shows the PageSpeed score for the page being analyzed. For example:

PageSpeed Score: 89

<script>
callbacks.displayPageSpeedScore = function(result) {
  var score = result.score;
  // Construct the query to send to the Google Chart Tools.
  var query = [
    'chtt=Page+Speed+score:+' + score,
    'chs=180x100',
    'cht=gom',
    'chd=t:' + score,
    'chxt=x,y',
    'chxl=0:|' + score,
  ].join('&');
  var i = document.createElement('img');
  i.src = CHART_API_URL + query;
  document.body.insertBefore(i, null);
};
</script>

Example 2: Display top PageSpeed suggestions

This example displays the names of the top PageSpeed suggestions for the page being analyzed, as an unordered list. For example:

  • Leverage browser caching
  • Defer parsing of JavaScript
  • Minify HTML
  • Minify JavaScript

Note: The data needed to display full PageSpeed results is provided by the PageSpeed Insights API, but in order to keep the example simple, not all of that data is used here.

<script>
callbacks.displayTopPageSpeedSuggestions = function(result) {
  var results = [];
  var ruleResults = result.formattedResults.ruleResults;
  for (var i in ruleResults) {
    var ruleResult = ruleResults[i];
    // Don't display lower-impact suggestions.
    if (ruleResult.ruleImpact < 3.0) continue;
    results.push({name: ruleResult.localizedRuleName,
                  impact: ruleResult.ruleImpact});
  }
  results.sort(sortByImpact);
  var ul = document.createElement('ul');
  for (var i = 0, len = results.length; i < len; ++i) {
    var r = document.createElement('li');
    r.innerHTML = results[i].name;
    ul.insertBefore(r, null);
  }
  if (ul.hasChildNodes()) {
    document.body.insertBefore(ul, null);
  } else {
    var div = document.createElement('div');
    div.innerHTML = 'No high impact suggestions. Good job!';
    document.body.insertBefore(div, null);
  }
};

// Helper function that sorts results in order of impact.
function sortByImpact(a, b) { return b.impact - a.impact; }
</script>

Example 3: Display a resource size breakdown pie chart

This example displays a pie chart that shows the resource size breakdown of the page being analyzed. For example:

<script>
var RESOURCE_TYPE_INFO = [
  {label: 'JavaScript', field: 'javascriptResponseBytes', color: 'e2192c'},
  {label: 'Images', field: 'imageResponseBytes', color: 'f3ed4a'},
  {label: 'CSS', field: 'cssResponseBytes', color: 'ff7008'},
  {label: 'HTML', field: 'htmlResponseBytes', color: '43c121'},
  {label: 'Flash', field: 'flashResponseBytes', color: 'f8ce44'},
  {label: 'Text', field: 'textResponseBytes', color: 'ad6bc5'},
  {label: 'Other', field: 'otherResponseBytes', color: '1051e8'},
];

callbacks.displayResourceSizeBreakdown = function(result) {
  var stats = result.pageStats;
  var labels = [];
  var data = [];
  var colors = [];
  var totalBytes = 0;
  var largestSingleCategory = 0;
  for (var i = 0, len = RESOURCE_TYPE_INFO.length; i < len; ++i) {
    var label = RESOURCE_TYPE_INFO[i].label;
    var field = RESOURCE_TYPE_INFO[i].field;
    var color = RESOURCE_TYPE_INFO[i].color;
    if (field in stats) {
      var val = Number(stats[field]);
      totalBytes += val;
      if (val > largestSingleCategory) largestSingleCategory = val;
      labels.push(label);
      data.push(val);
      colors.push(color);
    }
  }
  // Construct the query to send to the Google Chart Tools.
  var query = [
    'chs=300x140',
    'cht=p3',
    'chts=' + ['000000', 16].join(','),
    'chco=' + colors.join('|'),
    'chd=t:' + data.join(','),
    'chdl=' + labels.join('|'),
    'chdls=000000,14',
    'chp=1.6',
    'chds=0,' + largestSingleCategory,
  ].join('&');
  var i = document.createElement('img');
  i.src = 'http://chart.apis.google.com/chart?' + query;
  document.body.insertBefore(i, null);
};
</script>

Demo Video

PageSpeed Insights API demo at Google I/O BootCamp 2011.