简体   繁体   中英

Using GTmetrix REST API v2.0 in R

I am trying to integrate the performance testing of certain websites using GTmetrix. With the API, I am able to run the test and pull the results using the SEO connector tool in Microsoft Excel. However, it uses the xml with older version of API, and some new tests are not available in this. The latest version is 2.0

The link for the xml is here: GTmetrix XML for API 0.1 .

I tried using the libraries httr and jsonlite. But, I don't know how authenticate with API, run the test and extract the results.

The documentation for API is available at API Documentation .

library(httr)
library(jsonlite)

url  <- "https://www.berkeley.edu" # URL to be tested
location <- 1 # testing Location
browser <- 3 # Browser to be used for testing
res  <- GET("https://gtmetrix.com/api/gtmetrix-openapi-v2.0.json")
data <- fromJSON(rawToChar(res$content))

Pretty straightforward, actually:

0. Set test parameters.

# Your api key from the GTmetrix console
api_key <- "[Key]"

# URL to test.
# All attributes except URL are optional and availability of options
# may depend on the tier of your account.
url <- "https://www.worldwildlife.org/"

1. Start a test

res_test_start  <- httr::POST(
    url = "https://gtmetrix.com/api/2.0/tests",
    httr::authenticate(api_key, ""),
    httr::content_type("application/vnd.api+json"),
    body = jsonlite::toJSON(
        list(
            "data" = list(
                "type" = "test",
                "attributes" = list(
                    "url" = url
                    # Optional attributes would go here.
                )
            )
        ),
        auto_unbox = TRUE
    ),
    encode = "raw"
)

2. Get test ID

test_id <- jsonlite::fromJSON(rawToChar(res_test_start$content))$data$id

3. Get report ID

# Wait a bit, as generating the report can take some time.
res_test_status <- httr::GET(
    url = paste0("https://gtmetrix.com/api/2.0/tests/", test_id),
    httr::authenticate(api_key, ""),
    httr::content_type("application/vnd.api+json")
)

# If this returns the test ID, the report is not ready, yet.
report_id <- jsonlite::fromJSON(rawToChar(res_test_status$content))$data$id

4. Get report

res_report <- httr::GET(
    url = paste0("https://gtmetrix.com/api/2.0/reports/", report_id),
    httr::authenticate(api_key, ""),
    httr::content_type("application/vnd.api+json")
)

# The report is a nested list with the results as you know them from GTmetrix.
report <- jsonlite::fromJSON(rawToChar(res$content))

I'm kinda tempted to build something for this as there seems to be no R library for it...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM