Automating functionality exams on your WP Company with PageSpeed Insights API

by | Feb 10, 2026 | Etcetera | 0 comments

As your corporate supplies further consumers, maintaining most sensible capability all the way through all of the web pages you place up can in brief turn out to be an issue. Poorly coded plugins, unoptimized photos, and third-party scripts can slow down your consumer web pages and step-by-step lower PageSpeed Insights (PSI) ratings.

As a substitute of manually checking each and every WordPress web site, you’ll automate capability monitoring all the way through your entire web pages and pay attention to investigating anomalies only once they rise up, saving your body of workers hours of work each and every month via simple, surroundings pleasant computerized tests.

In this article, you’ll learn how to automate your workflow for monitoring the capability of your entire corporate’s Kinsta-hosted WordPress web pages via using the Kinsta API and Google PageSpeed Insights API together. As a final step, you’ll learn how to proportion this data in conjunction with your body of workers in real-time using Slack webhooks and automate the process with a cron activity.

Exciting, right kind? Let’s get started.

Workflow evaluate: Kinsta to PageSpeed Insights to Slack

The script links 3 APIs. Kinsta, Google PageSpeed Insights, and Slack, to automate web site capability monitoring.

Get began via querying the Kinsta API to fetch your internet web page domains and environments. This promises your house tick list stays provide as you add consumer web pages.

Then, for each and every web site returned throughout the Kinsta API, your script uses the Google PSI API to extract key metrics: Potency Score (0–100), First Contentful Paint (FCP), and Biggest Contentful Paint (LCP).

In any case, the script posts the ones metrics, web site name, the three ratings, and a PageSpeed Insights link to a delegated Slack channel.

Putting in place the apparatus

Previous than coding, generate two API keys and make rapid configurations.

The use of the Kinsta API: Check permissions and generate your API key

The Kinsta API requires an API key generated from an account with explicit permissions. For our example, it will have to be the company owner or a company administrator.

To create a Kinsta API key, log in to MyKinsta and follow the ones steps:

  • Navigate to the API Keys internet web page (Your name > Company settings > API Keys).
  • Click on on Create API Key.
  • Set Expiry and gives your key a novel name.
  • Click on on Generate.
Create an API key in MyKinsta.
Create an API key in MyKinsta.

Practice that that’s the one time you’ll see your API key. Replica it and store it in a safe place.

The second issue you need is your MyKinsta company ID. You’ll merely to search out it inside the query string of your MyKinsta dashboard URL (search for the idCompany parameter).

With this data, you’ll get right to use the Kinsta API and use cURL to request a list of your company web pages. Open your favorite command-line instrument and enter the following command, converting and in conjunction with your credentials.

curl -X GET "https://api.kinsta.com/v2/web pages?company=" 
	 -H "Authorization: Bearer "

If your company ID and API key are proper, you will have to download a JSON response structured as follows:

{
	"company": {
		"web pages": [
			{
				"id": "YOUR_SITE_ID",
				"name": "my-wordpress-website",
				"display_name": "My WordPress website",
				"status": "live",
				"site_labels": []
			}
		]
	}
}

As you’ll see, this response is missing an essential piece of information—the internet web page URL. To retrieve the primary house for each and every surroundings, you’ll add the parameter include_environments=true to the query string. With this parameter, the API moreover returns detailed data for each and every surroundings (live and staging), at the side of the primary house. Right here’s a generic response:

{
	"company": {
		"web pages": [
			{
				"id": "54fb80af-576c-4fdc-ba4f-b596c83f15a1",
				"name": "firstsite",
				"display_name": "First site",
				"status": "live",
				"siteLabels": [
					{
						"id": "54fb80af-576c-4fdc-ba4f-b596c83f15a1",
						"name": "Do not remove"
					}
				],
				"environments": [
					{
						"id": "54fb80af-576c-4fdc-ba4f-b596c83f15a1",
						"name": "live",
						"display_name": "Live",
						"is_blocked": false,
						"id_edge_cache": "54fb80af-576c-4fdc-ba4f-b596c83f15a1",
						"cdn_cache_id": "54fb80af-576c-4fdc-ba4f-b596c83f15a1",
						"is_opt_out_from_automatic_php_update": false,
						"web_root": "/release_v1",
						"image_optimization_type": "lossy",
						"is_additional_sftp_accounts_enabled": false,
						"is_premium": false,
						"wordpress_version": "6.3.1",
						"domains": [ ... ],
						"primaryDomain": {
							"identification": "54fb80af-576c-4fdc-ba4f-b596c83f15a1",
							"name": "example.com",
							"site_id": "54fb80af-576c-4fdc-ba4f-b596c83f15a1",
							"is_active": true,
							"type": "live"
						},
						"ssh_connection": { ... }
						},
						"container_info": { ... }
					}
				]
			}
		]
	}
}

Next, you need to generate a Google PageSpeed Insights device and API key.

See also  Reasonable WordPress Internet hosting Choices With Just right Options » Discovering Your…

Generate an API Key for Google PageSpeed Insights

Your next step is to create an API key to get right to use the Google PageSpeed Insights service. Log in to the Google Cloud Console and follow the ones steps:

Step 1: Create a brand spanking new mission or open an present one. For this newsletter, we created a brand spanking new Potency Monitoring mission.

Performance Monitoring project's page in the Google Cloud console
Potency Monitoring mission’s internet web page inside the Google Cloud console

Step 2: Navigate to APIs & Products and services and merchandise > Library, then search for PageSpeed Insights API at the bottom of the internet web page and click on on on the button.

Google Cloud API library
Make a selection PageSpeed Insights API inside the Google Cloud API Library

Step 3: On the next internet web page, click on on Permit.

Enable PageSpeed Insights API
Permit PageSpeed Insights API

Step 4: Click on on Create credentials inside the Credentials tab.

Create PSI API credentials
Create PSI API credentials

Step 5: For added protection, we propose surroundings restrictions for the newly created key via selecting only the PageSpeed Insights API.

Set restrictions to PageSpeed Insights API
Set restrictions to PageSpeed Insights API

Your PageSpeed Insights API secret’s now ready to use. One last service will have to be configured. You want to create a brand spanking new Slack app.

Create a Slack app and configure the Incoming Webhook

To send messages to a selected Slack channel, you need to create a Slack device. Apply the ones steps:

Step 1: Must you actively use Slack to collaborate in conjunction with your body of workers, then you definately’ve an full of life workspace. If not, consult with the Slack documentation to create one. For this example, we will think that you simply’ve an present My Company workspace.

Step 2: Transfer to the Slack API dashboard and click on on Create an App (or Create New App if this isn’t your first app).

Slack API dashboard
Create your first Slack app.

Step 3: You’ll be asked to configure your app’s scopes and settings. Make a selection From Scratch.

Create a Slack App from scratch.
Create a Slack App from scratch.

Step 4: Next, give your device a name (e.g., Potency Bot) and make a selection your workspace.

Choose App Name and select a workspace
Make a selection App Determine and make a selection a workspace

Step 5: Make a selection Incoming Webhooks from the left sidebar, then click on on On. Next, click on on Add New Webhook at the bottom of the internet web page.

Activate Incoming Webhooks
Activate Incoming Webhooks

Step 6: Replica the Webhook URL and put it aside for longer term reference.

Webhook URLs for your workspace
Webhook URLs in your workspace

You at this time have the entire thing you need to create a script that allows you to automatically proportion your internet web page’s capability metrics in conjunction with your body of workers on Slack. It’s time to dive into the code.

A PHP script to automate capability monitoring

Your next step is to create a script that communicates with the three aforementioned products and services and merchandise so to automatically computer screen the capability of all of the corporate’s consumer web pages hosted on Kinsta.

Step 1: Script configuration

For your favorite code editor, create a brand spanking new .php report and add the following code:

<?php

$kinsta_api_key	 = 'YOUR_KINSTA_API_KEY';
$kinsta_company_id  = 'YOUR_COMPANY_UUID';
$google_api_key	 = 'YOUR_GOOGLE_API_KEY';
$slack_webhook_url  = 'YOUR_SLACK_WEBHOOK_URL';

echo "--- STARTING PERFORMANCE MONITORING ---n";

Trade the placeholders in conjunction with your actual data that you just retrieved earlier.

Step 2: Use the Kinsta API to retrieve a list of company web pages

To get the tick list of internet websites in your Kinsta account, you need to use Kinsta API v2 and the /web pages endpoint.

Proper right here’s how you’ll be able to get right to use the API by means of cURL:

// 1. Fetch the tick list of internet websites from Kinsta
$url_kinsta = "https://api.kinsta.com/v2/web pages?company=" . $kinsta_company_id . "&include_environments=true";
$ch = curl_init($url_kinsta);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $kinsta_api_key]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res_kinsta = curl_exec($ch);
$data_kinsta = json_decode($res_kinsta, true);
curl_close($ch);

$web pages = $data_kinsta['company']['sites'] ?? [];
echo "Came upon " . depend($web pages) . " web pages to research.n";

Practice that we used the query parameter includes_environments=true to retrieve surroundings details (live and staging).

Next, query the Google PSI API and send the guidelines to the Slack app.

PageSpeed Insights metrics and Slack notifications

Now, you need to send the URL of each and every retrieved web site to the PageSpeed Insights API. While you call the service, PageSpeed Insights runs a capability check and returns an object containing capability metrics. Your script will send this data to the Slack API, which will generate the corresponding messages.

Proper right here’s the code to be able to upload on your script:

foreach ($web pages as $web site) {
	$site_label = $web site['display_name'];
	$primary_domain = "";

	// 2. Search the downloaded data at once for the live surroundings
	$environments = $web site['environments'] ?? [];

	foreach ($environments as $env) {
		if ($env['name'] === 'live') {
			$raw_domain = $env['primaryDomain'] ?? $env['primary_domain'] ?? null;
			$primary_domain = is_array($raw_domain) ? ($raw_domain['name'] ?? "") : $raw_domain;
			damage;
		}
	}

	if (empty($primary_domain)) {
		echo "Skipping $site_label (No Reside house found out).n";
		continue;
	}

	echo "Examining $primary_domain... ";

	// 3. PageSpeed analysis
	$psi_url = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://" . urlencode($primary_domain) . "&key=$google_api_key&elegance=capability&methodology=mobile";
	
	$res_psi = @file_get_contents($psi_url);
	if ($res_psi === false) {
		echo "PSI Error.n";
		continue;
	}

	$data_psi = json_decode($res_psi, true);

	$ranking = ($data_psi['lighthouseResult']['categories']['performance']['score'] ?? 0) * 100;
	$fcp   = $data_psi['lighthouseResult']['audits']['first-contentful-paint']['displayValue'] ?? 'N/A';
	$lcp   = $data_psi['lighthouseResult']['audits']['largest-contentful-paint']['displayValue'] ?? 'N/A';

	// 4. Send rich notification to Slack
	$report_link = "https://pagespeed.web.dev/analysis?url=https://" . $primary_domain . "&methodology=mobile";
	
	$slack_msg = [
		"text" => "🚀 *Performance Report: $site_label*nURL: `https://$primary_domain` nn" .
			"• *Score:* `$score` n" .
			"• *FCP:* $fcp n" .
			"• *LCP:* $lcpnn" .
			"[  ]"
	];

	$ch = curl_init($slack_webhook_url);
	curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($slack_msg));
	curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_exec($ch);
	curl_close($ch);

	echo "Finished.n";
}

echo "--- MONITORING COMPLETED ---n";

In brief, this code iterates over the elements of the $web pages array. For each and every part of the array, it fetches Core Internet Vitals and posts a message to Slack.

See also  X Marks The Spot: What’s to Come After Twitter’s Rebrand?

Testing the script

You’ll be able to connect in conjunction with your container the use of SSH and run your PHP script at once from the terminal. This allows you to in brief troubleshoot your script and procure capability results in Slack in real-time.

In MyKinsta, navigate to WordPress Web pages > Internet web page Determine. Scroll all of the approach all the way down to the Primary SFTP/SSH particular person segment and to search out the SSH terminal command field. It will have to look something like this:

ssh wordpress@host-name -p port-number

Replica the SSH terminal command and paste it into the terminal. You’ll be prompted to enter the password equipped within the identical segment. Press Enter, and you’ll be connected on your container surroundings.

SSH connection to Kinsta
SSH connection to Kinsta

Now you’ll be able to test your code. From the command line, navigate to the folder where you uploaded the script. In this example, we used the public folder:

cd public

Next, use the following command to run the script:

php performance-monitor.php

The script echoes a message for each and every movement it performs. As quickly because it has finished running, you will have to see a list of messages similar to the following:

--- STARTING FULL PERFORMANCE MONITORING ---
Came upon 5 web pages to research.
Examining site1.kinsta.cloud... Finished.
Examining site2.kinsta.cloud... Finished.
Examining site3.kinsta.cloud... Finished.
Examining example.com... Finished.
Examining site5.kinsta.cloud... Finished.
--- MONITORING COMPLETED ---

If PSI fails to respond in a neatly timed way, the script moves without delay to the next web site. In this case, you’ll see a message that looks like this:

--- STARTING FULL PERFORMANCE MONITORING ---
Came upon 5 web pages to research.
Examining site1.kinsta.cloud... Finished.
Examining site2.kinsta.cloud... Finished.
Examining site3.kinsta.cloud... Finished.
Examining example.com... PSI Error.
Examining site5.kinsta.cloud... Finished.
--- MONITORING COMPLETED ---

For the reason that script processes Google PSI responses, it sends a message on your Slack channel. For each and every web site successfully analyzed via PSI, you will have to see a Slack message pretty similar to the following:

Automated performance report on Slack
Automatic capability report on Slack

Awesome. You’ve merely created your computerized monitoring machine.

Now, it’s possible you’ll want to control it to fit your explicit needs. As an example, for individuals who arrange a lot of consumer web pages, sending a Slack message for each and every web site might be inefficient.

You have to, however, prepare a scenario that tests the web site’s basic ranking and sends a message to the Slack channel only if the value returned throughout the PSI API is below a specified threshold (e.g., 90). The following code would do the trick:

$threshold = 90;

// 4. Send rich notification to Slack
// The alert is led to only if the existing ranking is strictly not up to our limit.
if ($ranking  ]"
	];

	// Execute the CURL request to the Slack Webhook
	$ch = curl_init($slack_webhook_url);
	curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($slack_msg));
	curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_exec($ch);
	curl_close($ch);

	echo "Finished.n";
 else {
	echo "Score is highest ($ranking). No alert sent.n";
}

Change your script, save the report, and upload it over again. Then, hook up with the server by means of SSH, navigate to the proper folder, and run the following command over again:

php performance-monitor.php

Must you decided on a singular name in your script, control the command accordingly.

The terminal will have to now show a series of messages similar to the following:

--- STARTING FULL PERFORMANCE MONITORING ---
Came upon 5 web pages to research.
Examining site1.kinsta.cloud... Score is highest (100). No alert sent.
Examining site2.kinsta.cloud... Score is highest (95). No alert sent.
Examining site3.kinsta.cloud... Score is highest (100). No alert sent.
Examining example.com... Score below threshold. Sending Slack alert... Finished.
Examining site5.kinsta.cloud... Score below threshold. Sending Slack alert... Finished.
--- MONITORING COMPLETED ---

In Slack, you’ll download a message for each and every web site with an basic ranking below the 90 threshold.

An automated performance alert in Slack
An automated capability alert in Slack

That’s great, isn’t it? Then again you’ll be able to optimize the process even further. Wouldn’t you like to save some a lot more time via running the script automatically at set sessions without having to get right to use your command-line instrument?

See also  5 Lead Era Methods For Entrepreneurs

Positive, you guessed it. You want a cron job.

Automate the process using a cron job

There are a selection of ways to organize a cron job on Kinsta. Although you’ll be able to do it thru WordPress, Kinsta consumers can upload server cron jobs to each and every web site container.

To organize a cron job on Kinsta, create a cron command and add it on your container’s crontab report by means of SSH.

As an example, it is advisable use a command like the following:

0 10 * * * /usr/bin/php /www/yoursite_123/public/your-script.php >> /www/yoursite_123/performance_monitor.log 2>&1

Here is what this command does:

  • 0 10 * * * gadgets the script to be finished every day at 10 AM.
  • /usr/bin/php is the absolute path of the PHP interpreter on the server.
  • /www/yoursite_123/public/your-script.php is the absolute path of the script. Keep in mind to check the path and the actual name of your script on the server.
  • The >> operator (append redirection) appends new data to the top of the required report.
  • /www/yoursite_123/performance_monitor.log indicates the report by which all text printed throughout the script may also be saved.
  • The 2>&1 command instructs the server to direct errors to the identical report.

We will be able to not discuss cron directions in more part proper right here. You’ll be able to consult with the documentation from The Open Team or use a crontab instrument, an identical to Crontab Generator or Cronitor.

After construction your cron command, you need to be able to upload it on your web site container. You’ll be able to each ask our toughen body of workers to do this for you or do it yourself by means of SSH. If you choose the latter, get began via typing the following command:

crontab -e

You’ll be able to be asked to make a choice an editor. Make a selection “nano” should you don’t seem to be positive.

Inside the editor, paste your command at the end of the report. Save the report and return to the command line. You will have to then see a message confirming that your changes have been completed successfully.

crontab putting in place new crontab

That’s it. The script will now run at set sessions and send a message to the Slack channel of your variety with the requested metrics in your consumer web pages which could be performing poorly.

Scaling up: What else can you automate with the Kinsta API?

The script presented in this article will also be customized and expanded further. As an example, it is advisable mix other products and services and merchandise, an identical to Trello or Asana, export data, or send periodic email digests to consumers.

Automating your capability tests to your consumers’ web pages is just the beginning. Integrating the Kinsta API in conjunction with your body of workers’s day by day apparatus can turn out to be your corporate’s operations via eliminating information web site regulate and maintenance tasks, making improvements to efficiency, and decreasing working prices. You’ll moreover enhance service prime quality, cut back provide cases, and ensure the best possible experience in your consumers.

The Kinsta API lets you automate more than a few duties, at the side of growing staging environments, selectively pushing changes from staging to production, having access to error logs, clearing the website cache, managing backups, and further. The ones choices make managing WordPress web pages rapid and easy, allowing you to scale with self trust.

Ready to take your corporate to the next level? Uncover our plans or touch our gross sales staff to speak about your explicit needs.

Glad scaling!

The put up Automating functionality exams on your WP Company with PageSpeed Insights API seemed first on Kinsta®.

WP Hosting

[ continue ]

0 Comments

Submit a Comment

DON'T LET YOUR WEBSITE GET DESTROYED BY HACKERS!

Get your FREE copy of our Cyber Security for WordPress® whitepaper.

You'll also get exclusive access to discounts that are only found at the bottom of our WP CyberSec whitepaper.

You have Successfully Subscribed!