Automating functionality exams on your WP Company with PageSpeed Insights API

by | Feb 10, 2026 | Etcetera | 0 comments

As your corporate supplies further customers, maintaining best capability all through all the internet sites you put up can in brief develop into an issue. Poorly coded plugins, unoptimized footage, and third-party scripts can slow down your client internet sites and step-by-step lower PageSpeed Insights (PSI) scores.

Instead of manually checking each and every WordPress website online, you’ll automate capability monitoring all through your entire internet sites and be aware of investigating anomalies only once they get up, saving your body of workers hours of work each and every month through simple, setting pleasant automated assessments.

In this article, you’ll learn how to automate your workflow for monitoring the capability of your entire corporate’s Kinsta-hosted WordPress internet sites thru the usage of the Kinsta API and Google PageSpeed Insights API together. As a final step, you’ll learn how to share this knowledge at the side of your body of workers in real-time the usage of Slack webhooks and automate the process with a cron activity.

Exciting, right kind? Let’s get started.

Workflow overview: Kinsta to PageSpeed Insights to Slack

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

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

Then, for each and every website online returned in the course of the Kinsta API, your script uses the Google PSI API to extract key metrics: Potency Ranking (0–100), First Contentful Paint (FCP), and Biggest Contentful Paint (LCP).

In the end, the script posts the ones metrics, website online name, the three scores, and a PageSpeed Insights link to a delegated Slack channel.

Putting in place the apparatus

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

The use of the Kinsta API: Take a look at permissions and generate your API key

The Kinsta API requires an API key generated from an account with specific permissions. For our example, it should 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 unique 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. Copy it and store it in a secure 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 knowledge, you’ll get entry to the Kinsta API and use cURL to request an inventory of your company internet sites. Open your favorite command-line software and enter the following command, converting and at the side of your credentials.

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

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

{
	"company": {
		"internet sites": [
			{
				"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 knowledge—the internet web page URL. To retrieve the main house for each and every environment, 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 environment (are living and staging), in conjunction with the main house. Right here’s a generic response:

{
	"company": {
		"internet sites": [
			{
				"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,
							"sort": "are living"
						},
						"ssh_connection": { ... }
						},
						"container_info": { ... }
					}
				]
			}
		]
	}
}

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

See also  How one can Upload Customized Columns to the WordPress Customers Dashboard

Generate an API Key for Google PageSpeed Insights

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

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

Performance Monitoring project's page in the Google Cloud console
Potency Monitoring project’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
Select 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 additonal protection, we advise setting restrictions for the newly created key thru 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 should be configured. You need 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. Observe the ones steps:

Step 1: Must you actively use Slack to collaborate at the side of your body of workers, then you definately’ve an vigorous 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. Select 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 select your workspace.

Choose App Name and select a workspace
Select App Establish and select a workspace

Step 5: Select 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: Copy the Webhook URL and put it aside for long run reference.

Webhook URLs for your workspace
Webhook URLs for your workspace

You at the moment have the entire thing you need to create a script that allows you to routinely share your internet web page’s capability metrics at the side of 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 that you can routinely display screen the capability of all the corporate’s client internet sites 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 at the side of your precise data that you just retrieved earlier.

Step 2: Use the Kinsta API to retrieve an inventory of company internet sites

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

Proper right here’s how you can get entry to the API by way of cURL:

// 1. Fetch the tick list of internet websites from Kinsta
$url_kinsta = "https://api.kinsta.com/v2/internet sites?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);

$internet sites = $data_kinsta['company']['sites'] ?? [];
echo "Found out " . depend($internet sites) . " internet sites to research.n";

Practice that we used the query parameter includes_environments=true to retrieve environment details (are living and staging).

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

PageSpeed Insights metrics and Slack notifications

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

Proper right here’s the code in an effort to upload to your script:

foreach ($internet sites as $website online) {
	$site_label = $website online['display_name'];
	$primary_domain = "";

	// 2. Search the downloaded data immediately for the are living environment
	$environments = $website online['environments'] ?? [];

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

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

	echo "Analyzing $primary_domain... ";

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

	$data_psi = json_decode($res_psi, true);

	$score = ($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=cell";
	
	$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 "Accomplished.n";
}

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

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

See also  Divi Product Spotlight: Slider Mega Pack

Checking out the script

You can connect at the side of your container the use of SSH and run your PHP script immediately from the terminal. This lets you in brief troubleshoot your script and procure capability results in Slack in real-time.

In MyKinsta, navigate to WordPress Web sites > Internet web page Establish. Scroll all of the manner right down to the Primary SFTP/SSH individual segment and to search out the SSH terminal command field. It should look something like this:

ssh wordpress@host-name -p port-number

Copy the SSH terminal command and paste it into the terminal. You’ll be caused to enter the password provided within the equivalent segment. Press Enter, and you’ll be attached to your container environment.

SSH connection to Kinsta
SSH connection to Kinsta

Now you can 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 working, you should see an inventory of messages similar to the following:

--- STARTING FULL PERFORMANCE MONITORING ---
Found out 5 internet sites to research.
Analyzing site1.kinsta.cloud... Accomplished.
Analyzing site2.kinsta.cloud... Accomplished.
Analyzing site3.kinsta.cloud... Accomplished.
Analyzing example.com... Accomplished.
Analyzing site5.kinsta.cloud... Accomplished.
--- MONITORING COMPLETED ---

If PSI fails to respond in a smartly timed method, the script moves immediately to the next website online. In this case, you’ll see a message that looks like this:

--- STARTING FULL PERFORMANCE MONITORING ---
Found out 5 internet sites to research.
Analyzing site1.kinsta.cloud... Accomplished.
Analyzing site2.kinsta.cloud... Accomplished.
Analyzing site3.kinsta.cloud... Accomplished.
Analyzing example.com... PSI Error.
Analyzing site5.kinsta.cloud... Accomplished.
--- MONITORING COMPLETED ---

For the reason that script processes Google PSI responses, it sends a message to your Slack channel. For each and every website online successfully analyzed thru PSI, you should see a Slack message beautiful similar to the following:

Automated performance report on Slack
Automatic capability report on Slack

Awesome. You’ve merely created your automated monitoring system.

Now, you could need to control it to fit your specific needs. As an example, for many who arrange a variety of client internet sites, sending a Slack message for each and every website online might be inefficient.

It is advisable to, on the other hand, organize a scenario that assessments the website online’s basic score and sends a message to the Slack channel only if the price returned in the course of 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 caused only if the prevailing score is strictly lower than our limit.
if ($score  ]"
	];

	// 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 "Accomplished.n";
 else {
	echo "Ranking is easiest ($score). No alert sent.n";
}

Substitute your script, save the report, and upload it all over again. Then, connect to the server by way of SSH, navigate to the best folder, and run the following command all over again:

php performance-monitor.php

Must you decided on a novel name for your script, control the command accordingly.

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

--- STARTING FULL PERFORMANCE MONITORING ---
Found out 5 internet sites to research.
Analyzing site1.kinsta.cloud... Ranking is easiest (100). No alert sent.
Analyzing site2.kinsta.cloud... Ranking is easiest (95). No alert sent.
Analyzing site3.kinsta.cloud... Ranking is easiest (100). No alert sent.
Analyzing example.com... Ranking below threshold. Sending Slack alert... Accomplished.
Analyzing site5.kinsta.cloud... Ranking below threshold. Sending Slack alert... Accomplished.
--- MONITORING COMPLETED ---

In Slack, you’ll download a message for each and every website online with an basic score 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 can optimize the process even further. Wouldn’t you prefer to save some a lot more time thru working the script routinely at set sessions without having to get entry to your command-line software?

See also  How HubSpot’s Hustle Staff Makes use of AI

Certain, you guessed it. You need a cron job.

Automate the process the usage of a cron job

There are a selection of tactics to prepare a cron job on Kinsta. Even though you can do it thru WordPress, Kinsta consumers can upload server cron jobs to each and every website online container.

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

For example, that you must 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 * * * devices 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. Take into account to check the path and the actual name of your script on the server.
  • The >> operator (append redirection) appends new data to the end of the required report.
  • /www/yoursite_123/performance_monitor.log indicates the report by which all text printed in the course of the script will also be saved.
  • The 2>&1 command instructs the server to direct errors to the equivalent report.

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

After construction your cron command, you need in an effort to upload it to your website online container. You can each ask our make stronger body of workers to try this for you or do it yourself by way of SSH. If you choose the latter, get began thru typing the following command:

crontab -e

You can be asked to select an editor. Select “nano” if you aren’t certain.

Throughout the editor, paste your command at the end of the report. Save the report and return to the command line. You should then see a message confirming that your changes were 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 for your client internet sites which may well be appearing poorly.

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

The script introduced in this article can be customized and expanded further. As an example, that you must mix other products and services and merchandise, an identical to Trello or Asana, export data, or send periodic email digests to customers.

Automating your capability assessments on your customers’ internet sites is just the beginning. Integrating the Kinsta API at the side of your body of workers’s daily apparatus can turn into your corporate’s operations thru eliminating information website online keep an eye on and maintenance tasks, improving efficiency, and decreasing working prices. You’ll moreover strengthen service top quality, cut back provide circumstances, and ensure the most productive conceivable enjoy for your customers.

The Kinsta API means that you can automate more than a few duties, in conjunction with growing staging environments, selectively pushing changes from staging to production, having access to error logs, clearing the website cache, managing backups, and additional. The ones choices make managing WordPress internet sites speedy 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 discuss your specific 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!