Examples

Warning

As long as major version of this library is 0 (i.e. library has version 0.x.y), API is not guaranteed to be compatible between versions. When you start using this library, please let the developer know about - I will bump the major version to 1, and usuall semver guatantees regarding version compatibility will be applied.

Simplest example

You already saw it on the main page:

import json
import python_gtmetrix2

api_key = "e8ddc55d93eb0e8281b255ea236dcc4f"    # your API key
url = "http://example.com"                      # URL to test

account = python_gtmetrix2.Account(api_key)     # init
test = account.start_test(url)                  # start test
test.fetch(wait_for_completion=True)            # wait for it to finish
report = test.getreport()                       # get test result

print(json.dumps(report, indent=2))             # do something useful with it

All the following examples are available in the github repo in “examples” subdir

On this page, only the most interesting part is shown - without include statements and if __name__ == "__main__" part which makes them into executable scripts.

Start multiple tests

Example which shows how to start multiple tests in parallel, wait for them to finish, and fetch reports for tests that completed successfully.

Note that GTmetrix limits the number of tests you can run in parallel (2 concurrent tests on a Basic account, 8 concurrent tests on a PRO account). This example does not impose any concurrency limits by itself, but instead relies on GTmetrix API to reply with 429 HTTP error and retries.

def main(api_key, urls):
    account = python_gtmetrix2.Account(api_key)

    print("=== starting tests ===")

    tests = []
    for url in urls:
        test = account.start_test(url)
        print(json.dumps(test))
        tests.append(test)

    print("=== wait for tests to finish ===")

    for test in tests:
        test.fetch(wait_for_completion=True)

    print("=== fetching report for each test ===")

    for test in tests:

        report = test.getreport()

        if report is None:
            print("No report for test %s" % test["id"])
        else:
            print(json.dumps(report, indent=2))

List recent tests

Example which shows what can be done with result of Account.list_tests() method.

You can either treat it as a JSON-like dict object, or use Test.getreport() function to get corresponding report, if it exists. Report is also a JSON-like dict object.

def main(api_key):
    account = python_gtmetrix2.Account(api_key)

    print("=== fetching tests ===")

    tests = account.list_tests()

    if len(tests) == 0:
        print("No tests found! Note that only tests started within last 24 hours are available via this API.")
        return

    for test in tests:
        print(json.dumps(test, indent=2))

    print("=== fetching report for each test ===")

    for test in tests:

        report = test.getreport()

        if report is None:
            print("No report for test %s" % test["id"])
        else:
            print(json.dumps(report, indent=2))

Operations on report

Example which shows some possible uses of report:

  • You can treat it as a JSON-like dict object and access any properties you want

  • You can request report to be deleted or retested

  • You can download a single report resource (such as a PDF version)

Also, this example demonstrates how you can work with JSON resources, like a har file.

Note how it uses Account.reportFromId() method to get report from its ID. When running examples, you can get report ID from “links.report” attribute of the test object (note that it points to the whole report URL, and the report ID is the part which comes after /reports/ part), or from report’s id attribute.

When using this library, you can also use Test.getreport() method to get report object for a specific test object.

def main(api_key, report_id, operation="print", *args):
    """Usage: %s api_key report_id [operation]
    or: %s api_key report_id getresource resource [filename]

    where operation is one of: print (default), delete, retest, size, getresource

    getresource operation requires one extra argument: what resource to get,
    and one optional: filename where to save it. If filename is not provided,
    resource is printed to stdout.
    """

    account = python_gtmetrix2.Account(api_key)
    report = account.reportFromId(report_id)

    if operation == "print":
        print(json.dumps(report, indent=2))
        # print(report["attributes"]["first_contentful_paint"])

    elif operation == "delete":
        report.delete()
        print("Report deleted.")

    elif operation == "retest":
        test = report.retest()
        print("new test:")
        print(json.dumps(test, indent=2))

    elif operation == "getresource":
        if len(args) not in [1, 2]:
            print("Usage: %s api_key report_id getresource resource [filename]" % sys.argv[0])
            print("If filename is not provided, resource is printed to stdout.")
            exit()
        getresource(report, *args)

    elif operation == "size":
        har = json.loads(report.getresource("net.har").decode())
        size_bytes = summarizeHar(har)
        size_kb = size_bytes / 1024
        size_mb = size_kb / 1024
        print("Total size of all resources, uncompressed: %d bytes = %.1f kb = %.1f MB" % (size_bytes, size_kb, size_mb))

    else:
        print("Usage: %s api_key report_id [operation]" % sys.argv[0])
        print("or: %s api_key report_id getresource resource [filename]" % sys.argv[0])
        print("where operation is one of: print (default), delete, retest, size, getresource")


def getresource(report, resource, filename=sys.stdout.buffer):
    """Gets report resource and saves it to filename (stdout by default)"""
    report.getresource(resource, filename)


def summarizeHar(har):
    """Given a har file (parsed json object), returns total size of all responses, in bytes."""
    return sum((entry["response"]["content"]["size"] for entry in har["log"]["entries"]))