As your company provides extra shoppers, keeping up top functionality throughout the entire websites you set up can briefly transform a problem. Poorly coded plugins, unoptimized pictures, and third-party scripts can decelerate your shopper websites and step by step decrease PageSpeed Insights (PSI) rankings.
As an alternative of manually checking every WordPress website, you’ll automate functionality tracking throughout all of your websites and concentrate on investigating anomalies handiest after they stand up, saving your staff hours of labor every month thru easy, environment friendly automatic exams.
On this article, you’ll learn to automate your workflow for tracking the functionality of all of your company’s Kinsta-hosted WordPress websites through the use of the Kinsta API and Google PageSpeed Insights API in combination. As a last step, you are going to learn to percentage this information along with your staff in real-time the use of Slack webhooks and automate the method with a cron activity.
Thrilling, proper? Let’s get began.
Workflow assessment: Kinsta to PageSpeed Insights to Slack
The script hyperlinks 3 APIs. Kinsta, Google PageSpeed Insights, and Slack, to automate website functionality tracking.
Get started through querying the Kinsta API to fetch your web page domain names and environments. This guarantees your area checklist remains present as you upload shopper websites.
Then, for every website returned through the Kinsta API, your script makes use of the Google PSI API to extract key metrics: Efficiency Rating (0–100), First Contentful Paint (FCP), and Greatest Contentful Paint (LCP).
In spite of everything, the script posts those metrics, website call, the 3 rankings, and a PageSpeed Insights hyperlink to a chosen Slack channel.
Putting in the equipment
Earlier than coding, generate two API keys and make fast configurations.
The usage of the Kinsta API: Test permissions and generate your API key
The Kinsta API calls for an API key generated from an account with particular permissions. For our instance, it must be the corporate proprietor or an organization administrator.
To create a Kinsta API key, log in to MyKinsta and observe those steps:
- Navigate to the API Keys web page (Your call > Corporate settings > API Keys).
- Click on Create API Key.
- Set Expiry and provides your key a singular call.
- Click on Generate.

Observe that that is the one time you’ll see your API key. Reproduction it and retailer it in a protected position.
The second one factor you want is your MyKinsta corporate ID. You’ll simply to find it within the question string of your MyKinsta dashboard URL (seek for the idCompany parameter).
With this information, you’ll get admission to the Kinsta API and use cURL to request a listing of your corporate websites. Open your favourite command-line device and input the next command, changing and along with your credentials.
curl -X GET "https://api.kinsta.com/v2/websites?corporate="
-H "Authorization: Bearer "
In case your corporate ID and API key are right kind, you must obtain a JSON reaction structured as follows:
{
"corporate": {
"websites": [
{
"id": "YOUR_SITE_ID",
"name": "my-wordpress-website",
"display_name": "My WordPress website",
"status": "live",
"site_labels": []
}
]
}
}
As you’ll see, this reaction is lacking an very important piece of data—the web page URL. To retrieve the principle area for every atmosphere, you’ll upload the parameter include_environments=true to the question string. With this parameter, the API additionally returns detailed information for every atmosphere (reside and staging), together with the principle area. Here’s a generic reaction:
{
"corporate": {
"websites": [
{
"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": {
"identity": "54fb80af-576c-4fdc-ba4f-b596c83f15a1",
"call": "instance.com",
"site_id": "54fb80af-576c-4fdc-ba4f-b596c83f15a1",
"is_active": true,
"kind": "reside"
},
"ssh_connection": { ... }
},
"container_info": { ... }
}
]
}
]
}
}
Subsequent, you want to generate a Google PageSpeed Insights software and API key.
Generate an API Key for Google PageSpeed Insights
The next move is to create an API key to get admission to the Google PageSpeed Insights carrier. Log in to the Google Cloud Console and observe those steps:
Step 1: Create a brand new venture or open an current one. For this text, we created a brand new Efficiency Tracking venture.

Step 2: Navigate to APIs & Services and products > Library, then seek for PageSpeed Insights API on the backside of the web page and click on at the button.

Step 3: At the subsequent web page, click on Allow.

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

Step 5: For extra safety, we suggest environment restrictions for the newly created key through settling on handiest the PageSpeed Insights API.

Your PageSpeed Insights API secret’s now able to make use of. One remaining carrier must be configured. You wish to have to create a brand new Slack app.
Create a Slack app and configure the Incoming Webhook
To ship messages to a particular Slack channel, you want to create a Slack software. Practice those steps:
Step 1: Should you actively use Slack to collaborate along with your staff, then you’ve an lively workspace. If no longer, discuss with the Slack documentation to create one. For this situation, we will be able to suppose that you’ve an current My Corporate workspace.
Step 2: Move to the Slack API dashboard and click on Create an App (or Create New App if this isn’t your first app).

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

Step 4: Subsequent, give your software a reputation (e.g., Efficiency Bot) and make a choice your workspace.

Step 5: Make a choice Incoming Webhooks from the left sidebar, then click on On. Subsequent, click on Upload New Webhook on the backside of the web page.

Step 6: Reproduction the Webhook URL and reserve it for long term reference.

You presently have the whole thing you want to create a script that permits you to mechanically percentage your web page’s functionality metrics along with your staff on Slack. It’s time to dive into the code.
A PHP script to automate functionality tracking
The next move is to create a script that communicates with the 3 aforementioned services and products as a way to mechanically visual display unit the functionality of the entire company’s shopper websites hosted on Kinsta.
Step 1: Script configuration
To your favourite code editor, create a brand new .php record and upload the next code:
Change the placeholders along with your exact information that you simply retrieved previous.
Step 2: Use the Kinsta API to retrieve a listing of corporate websites
To get the checklist of web sites on your Kinsta account, you want to make use of Kinsta API v2 and the /websites endpoint.
Right here’s how you'll get admission to the API by the use of cURL:
// 1. Fetch the checklist of web sites from Kinsta
$url_kinsta = "https://api.kinsta.com/v2/websites?corporate=" . $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);
$websites = $data_kinsta['company']['sites'] ?? [];
echo "Discovered " . rely($websites) . " websites to investigate.n";
Observe that we used the question parameter includes_environments=true to retrieve atmosphere main points (reside and staging).
Subsequent, question the Google PSI API and ship the information to the Slack app.
PageSpeed Insights metrics and Slack notifications
Now, you want to ship the URL of every retrieved website to the PageSpeed Insights API. Whilst you name the carrier, PageSpeed Insights runs a functionality test and returns an object containing functionality metrics. Your script will ship this information to the Slack API, which can generate the corresponding messages.
Right here’s the code so as to add in your script:
foreach ($websites as $website) {
$site_label = $website['display_name'];
$primary_domain = "";
// 2. Seek the downloaded information without delay for the reside atmosphere
$environments = $website['environments'] ?? [];
foreach ($environments as $env) {
if ($env['name'] === 'reside') {
$raw_domain = $env['primaryDomain'] ?? $env['primary_domain'] ?? null;
$primary_domain = is_array($raw_domain) ? ($raw_domain['name'] ?? "") : $raw_domain;
ruin;
}
}
if (empty($primary_domain)) {
echo "Skipping $site_label (No Are living area discovered).n";
proceed;
}
echo "Inspecting $primary_domain... ";
// 3. PageSpeed research
$psi_url = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://" . urlencode($primary_domain) . "&key=$google_api_key&class=functionality&technique=cellular";
$res_psi = @file_get_contents($psi_url);
if ($res_psi === false) {
echo "PSI Error.n";
proceed;
}
$data_psi = json_decode($res_psi, true);
$rating = ($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. Ship wealthy notification to Slack
$report_link = "https://pagespeed.internet.dev/research?url=https://" . $primary_domain . "&technique=cellular";
$slack_msg = [
"text" => "🚀 *Performance Report: $site_label*nURL: `https://$primary_domain` nn" .
"• *Score:* `$score` n" .
"• *FCP:* $fcp n" .
"• *LCP:* $lcpnn" .
"[ <$report_link|View Full Report> ]"
];
$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 "Executed.n";
}
echo "--- MONITORING COMPLETED ---n";
Briefly, this code iterates over the weather of the $websites array. For every component of the array, it fetches Core Internet Vitals and posts a message to Slack.
Trying out the script
You'll attach along with your container the use of SSH and run your PHP script without delay from the terminal. This permits you to briefly troubleshoot your script and obtain functionality leads to Slack in real-time.
In MyKinsta, navigate to WordPress Websites > Web page Identify. Scroll all the way down to the Number one SFTP/SSH person phase and to find the SSH terminal command box. It must glance one thing like this:
ssh wordpress@host-name -p port-number
Reproduction the SSH terminal command and paste it into the terminal. You’ll be precipitated to go into the password supplied in the similar phase. Press Input, and you are going to be hooked up in your container atmosphere.

Now you'll check your code. From the command line, navigate to the folder the place you uploaded the script. On this instance, we used the public folder:
cd public
Subsequent, use the next command to run the script:
php performance-monitor.php
The script echoes a message for every motion it plays. As soon as it has completed operating, you must see a listing of messages very similar to the next:
--- STARTING FULL PERFORMANCE MONITORING ---
Discovered 5 websites to investigate.
Inspecting site1.kinsta.cloud... Executed.
Inspecting site2.kinsta.cloud... Executed.
Inspecting site3.kinsta.cloud... Executed.
Inspecting instance.com... Executed.
Inspecting site5.kinsta.cloud... Executed.
--- MONITORING COMPLETED ---
If PSI fails to reply in a well timed approach, the script strikes directly to the following website. On this case, you are going to see a message that appears like this:
--- STARTING FULL PERFORMANCE MONITORING ---
Discovered 5 websites to investigate.
Inspecting site1.kinsta.cloud... Executed.
Inspecting site2.kinsta.cloud... Executed.
Inspecting site3.kinsta.cloud... Executed.
Inspecting instance.com... PSI Error.
Inspecting site5.kinsta.cloud... Executed.
--- MONITORING COMPLETED ---
Because the script processes Google PSI responses, it sends a message in your Slack channel. For every website effectively analyzed through PSI, you must see a Slack message lovely very similar to the next:

Superior. You’ve simply created your automatic tracking gadget.
Now, you might wish to regulate it to suit your particular wishes. For example, for those who set up loads of shopper websites, sending a Slack message for every website may well be inefficient.
It's essential, alternatively, arrange a situation that exams the website’s general rating and sends a message to the Slack channel provided that the worth returned through the PSI API is under a specified threshold (e.g., 90). The next code would do the trick:
$threshold = 90;
// 4. Ship wealthy notification to Slack
// The alert is brought about provided that the present rating is precisely less than our restrict.
if ($rating < $threshold) View Full Audit Report> ]"
];
// 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 "Executed.n";
else {
echo "Rating is perfect ($rating). No alert despatched.n";
}
Replace your script, save the record, and add it once more. Then, connect with the server by the use of SSH, navigate to the suitable folder, and run the next command once more:
php performance-monitor.php
Should you selected a unique call on your script, regulate the command accordingly.
The terminal must now display a chain of messages very similar to the next:
--- STARTING FULL PERFORMANCE MONITORING ---
Discovered 5 websites to investigate.
Inspecting site1.kinsta.cloud... Rating is perfect (100). No alert despatched.
Inspecting site2.kinsta.cloud... Rating is perfect (95). No alert despatched.
Inspecting site3.kinsta.cloud... Rating is perfect (100). No alert despatched.
Inspecting instance.com... Rating under threshold. Sending Slack alert... Executed.
Inspecting site5.kinsta.cloud... Rating under threshold. Sending Slack alert... Executed.
--- MONITORING COMPLETED ---
In Slack, you are going to obtain a message for every website with an general rating under the 90 threshold.

That’s nice, isn’t it? However you'll optimize the method even additional. Wouldn’t you favor to avoid wasting much more time through operating the script mechanically at set periods while not having to get admission to your command-line device?
Sure, you guessed it. You wish to have a cron activity.
Automate the method the use of a cron activity
There are a number of techniques to arrange a cron activity on Kinsta. Even if you'll do it thru WordPress, Kinsta customers can upload server cron jobs to every website container.
To arrange a cron activity on Kinsta, create a cron command and upload it in your container’s crontab record by the use of SSH.
For instance, it's good to use a command like the next:
0 10 * * * /usr/bin/php /www/yoursite_123/public/your-script.php >> /www/yoursite_123/performance_monitor.log 2>&1
Here's what this command does:
0 10 * * *units the script to be completed on a daily basis at 10 AM./usr/bin/phpis absolutely the trail of the PHP interpreter at the server./www/yoursite_123/public/your-script.phpis absolutely the trail of the script. Remember to test the trail and the true call of your script at the server.- The
>>operator (append redirection) appends new information to the tip of the desired record. /www/yoursite_123/performance_monitor.logsignifies the record wherein all textual content revealed through the script can be stored.- The
2>&1command instructs the server to direct mistakes to the similar record.
We can no longer speak about cron instructions in additional element right here. You'll discuss with the documentation from The Open Team or use a crontab device, equivalent to Crontab Generator or Cronitor.
After development your cron command, you want so as to add it in your website container. You'll both ask our improve staff to do that for you or do it your self by the use of SSH. If you select the latter, get started through typing the next command:
crontab -e
You'll be requested to choose an editor. Make a choice “nano” in case you are not sure.
Within the editor, paste your command on the finish of the record. Save the record and go back to the command line. You must then see a message confirming that your adjustments had been finished effectively.
crontab putting in new crontab
That’s it. The script will now run at set periods and ship a message to the Slack channel of your selection with the asked metrics on your shopper websites which might be acting poorly.
Scaling up: What else are you able to automate with the Kinsta API?
The script offered on this article may also be custom designed and expanded additional. For example, it's good to combine different services and products, equivalent to Trello or Asana, export information, or ship periodic e-mail digests to shoppers.
Automating your functionality exams for your shoppers’ websites is just the start. Integrating the Kinsta API along with your staff’s day-to-day equipment can develop into your company’s operations through getting rid of guide website control and upkeep duties, bettering potency, and decreasing working prices. You’ll additionally reinforce carrier high quality, scale back supply instances, and make sure the most efficient imaginable revel in on your shoppers.
The Kinsta API allows you to automate more than a few duties, together with growing staging environments, selectively pushing adjustments from staging to manufacturing, having access to error logs, clearing the website cache, managing backups, and extra. Those options make managing WordPress websites fast and simple, permitting you to scale with self belief.
In a position to take your company to the following degree? Discover our plans or touch our gross sales staff to talk about your particular wishes.
Satisfied scaling!
The publish Automating functionality exams on your WP Company with PageSpeed Insights API gave the impression first on Kinsta®.
WP Hosting