API reference¶
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.
Overview¶
User of this library is expected to interact primarily with the following three classes:
Account
, which is instantiated with your API key and is used for all API calls which don’t operate on a particular test or report. For example, API calls to start a new test (Account.start_test()
), or to get account information (Account.status()
).Test
, which corresponds to a requested test (which might be still running or already finished).Report
, which describes results of a successfully finished test.
Note that usually objects of Test
and Report
classes should
not be instantiated directly - users of this library are expected to use
methods of Account
class instead: for example,
Account.start_test()
to start a test, or Account.list_tests()
to get a list of recent tests. And then Test.getreport()
to get a report
for a finished test.
Also note that Test
and Report
classes are descendants of the
dict, so you can operate on as such: json.dumps()
them to inspect
their internals, and access their attributes same way as for a dict
.
Public API classes¶
- class python_gtmetrix2.Account(api_key, base_url='https://gtmetrix.com/api/2.0/', sleep_function=<built-in function sleep>)[source]¶
Bases:
object
Main entry point into this library
- Parameters
api_key (
str
) – your GTmetrix API key.base_url (str, optional) – base URL for all API requests - useful for testing or if someone implements a GTmetrix competitor with a compatible API, defaults to “https://gtmetrix.com/api/2.0/”
sleep_function (method, optional) – the function to execute when waiting between retries (after receiving a “429” response) - useful for testing, or if someone wants to add some logging or notification of a delayed request, defaults to
time.sleep()
- start_test(url, **attributes)[source]¶
Start a Test
- Parameters
url (str) – the URL to test.
You can pass additional parameters for the tests (like browser, location, desired report depth, etc) as extra keyword arguments, like this:
>>> account.start_test('http://example.com', report='none')
Or, if you prefer having a dict, you can use the
**kwargs
-style Python expansion, like this:>>> parameters={'location': '1', 'browser': '3', 'adblock': '1'} >>> account.start_test('http://example.com', **parameters)
Note that this method does not wait for the test to finish. For that, call
test.fetch(wait_for_completion=True)
after calling this method.
- list_tests(sort=None, filter=None, page_number=0)[source]¶
Get a list of recent tests.
Note that while reports are stored on GTmetrix servers for several (1 to 6) months, tests are deleted after 24 hours. Hence, this function lists only rather recent tests.
- Parameters
sort (str, optional) – Sort string by one of “created”, “started”, “finished”, optionally prefixed with “-” for reverse sorting, defaults to None (no sort).
filter (dict) – Filter tests - argument should be a dict of key/value pairs, where key is one of “state”, “created”, “started”, “finished”, “browser”, “location”, optionally postfixed with one of “:eq, :lt, :lte, :gt, :gte” and value is, well, value (string or number). Valid values for “state” are “queued”, “started”, “error”, and “completed”. “created”, “started” and “finished” are UNIX timestamps. “browser” and “location” are browser and location IDs.
- Return type
- Examples
To get all tests finished successfully within last 10 minutes:
>>> import time >>> now = int(time.time()) >>> tests = account.list_tests( ... filter={"state": "completed", "created:gt": (now-10*60)})
To get all tests which ended up with an error, and print the error message for each of them:
>>> tests = account.list_tests(filter={"state": "error"}) >>> for test in tests: ... print("Test %s failed: %s" % (test["id"], test["attributes"]["error"]))
- status()[source]¶
Get the current account details and status.
Returns
dict
with information about your api key, current API credit balance, and time of next credit refill (Unix timestamp).- Example
>>> account = Account("e8ddc55d93eb0e8281b255ea236dcc4f") >>> status = account.status() >>> print(json.dumps(status, indent=2))
would print something like this:
{ "type": "user", "id": "e8ddc55d93eb0e8281b255ea236dcc4f", "attributes": { "api_credits": 1497, "api_refill": 1618437519 } }
- class python_gtmetrix2.Test(requestor, data, sleep_function=<built-in function sleep>)[source]¶
Bases:
python_gtmetrix2._internals.Object
- fetch(wait_for_completion=False, retries=10)[source]¶
Ask API server for updated data regarding this test.
- getreport()[source]¶
Returns Report object for this test, if it is available.
Note that this function does not check whether the test has actually completed since the last call to API. For that, you should use method
fetch
first.Also note that even if report is finished (i.e. after
fetch(wait_for_completion=True)
returns), it’s not guaranteed that it completed successfully - it could have finished with an error - for example, due to certificate or connection error. In that case, your test will have status = “error” attribute, and also error attribute explaining what went wrong.- Return type
Report
or None
- class python_gtmetrix2.Report(requestor, data, sleep_function=<built-in function sleep>)[source]¶
Bases:
python_gtmetrix2._internals.Object
- delete()[source]¶
Delete the report.
Note that after executing this method, all other methods should error with a “404 Report not found” error.
- getresource(name, destination=None)[source]¶
Get a report resource (such as a PDF file, video, etc)
Depending on the value of
destination
parameter, it might be saved to a file, a file-like object, or returned to the caller. Be careful with the latter in case a file is too big, though.- Parameters
name (str) – Name of the desired resource. It can be either key of
report["links"]
dict (such as “report_pdf”, “lighthouse”, or “har”), or a filename to be appended to URL (such as “report.pdf”, “lighthouse.json”, or “net.har”). List of possible keys you can find by inspecting thereport["links"]
dict, and full list of possible filenames - at the GTmetrix API documentation: <https://gtmetrix.com/api/docs/2.0/#api-report-resource>destination (None or str or a file-like object) – Where to save the downloaded resource. If it is
None
, then resource is completely downloaded into RAM and returned to the caller. If it is a string, then the resource is saved into a file with that name. If it is a file-like object, thenshutil.copyfileobj()
is used to copy the resource into that object.