As your corporate supplies further customers, maintaining best capability all over all of the web pages you place up can in brief become an issue. Poorly coded plugins, unoptimized footage, and third-party scripts can slow down your consumer web pages and step-by-step lower PageSpeed Insights (PSI) scores.
As a substitute of manually checking each and every WordPress web site, you’ll automate capability monitoring all over your entire web pages and pay attention to investigating anomalies only when they rise up, saving your group of workers hours of work each and every month through simple, setting pleasant automated assessments.
In this article, you’ll discover ways to automate your workflow for monitoring the capability of your entire corporate’s Kinsta-hosted WordPress web pages via the usage of the Kinsta API and Google PageSpeed Insights API together. As a final step, you will discover ways to proportion this knowledge along side your group of workers in real-time the usage of Slack webhooks and automate the process with a cron activity.
Exciting, correct? Let’s get started.
Workflow evaluation: 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 Ranking (0–100), First Contentful Paint (FCP), and Largest Contentful Paint (LCP).
In any case, the script posts the ones metrics, web site 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 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 apply 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.

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 wish to have 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 web pages. Open your favorite command-line software and enter the following command, converting and along side 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 (are living and staging), along with 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": "are living"
},
"ssh_connection": { ... }
},
"container_info": { ... }
}
]
}
]
}
}
Next, you wish to have to generate a Google PageSpeed Insights instrument and API key.
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 provider. Log in to the Google Cloud Console and apply 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.

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

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

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

Step 5: For added protection, we advise setting restrictions for the newly created key via deciding on only the PageSpeed Insights API.

Your PageSpeed Insights API secret’s now in a position to use. One last provider will have to 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 wish to have to create a Slack instrument. Follow the ones steps:
Step 1: Must you actively use Slack to collaborate along side your group of workers, you then’ve an vigorous workspace. If now not, visit the Slack documentation to create one. For this case, we can think that you just’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).

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

Step 4: Next, give your instrument a name (e.g., Potency Bot) and choose your workspace.

Step 5: Choose 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.

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

You at the moment have the entire thing you wish to have to create a script that allows you to automatically proportion your internet web page’s capability metrics along side your group 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 could 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 document 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";
Alternate the placeholders along side your actual data that you just retrieved earlier.
Step 2: Use the Kinsta API to retrieve an inventory of company web pages
To get the tick list of internet websites in your Kinsta account, you wish to have to use Kinsta API v2 and the /web pages endpoint.
Proper right here’s how you can get entry to 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 "Found out " . depend($web pages) . " web pages to analyze.n";
Practice that we used the query parameter includes_environments=true to retrieve surroundings details (are living and staging).
Next, query the Google PSI API and send the ideas to the Slack app.
PageSpeed Insights metrics and Slack notifications
Now, you wish to have to send the URL of each and every retrieved web site to the PageSpeed Insights API. When you call the provider, PageSpeed Insights runs a capability take a look at 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 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 are living surroundings
$environments = $web site['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;
destroy;
}
}
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&method=mobile";
$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 . "&method=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 "Completed.n";
}
echo "--- MONITORING COMPLETED ---n";
In brief, this code iterates over the elements of the $web pages array. For each and every element of the array, it fetches Core Internet Vitals and posts a message to Slack.
Checking out the script
You’ll be able to connect along side 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 sites > Internet web page Establish. Scroll the entire manner right 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 brought on to enter the password provided within the identical segment. Press Enter, and you will be attached on your container surroundings.

Now you can take a look at 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 an inventory of messages similar to the following:
--- STARTING FULL PERFORMANCE MONITORING ---
Found out 5 web pages to analyze.
Analyzing site1.kinsta.cloud... Completed.
Analyzing site2.kinsta.cloud... Completed.
Analyzing site3.kinsta.cloud... Completed.
Analyzing example.com... Completed.
Analyzing site5.kinsta.cloud... Completed.
--- MONITORING COMPLETED ---
If PSI fails to respond in a neatly timed method, the script moves without delay to the next web site. In this case, you will see a message that looks like this:
--- STARTING FULL PERFORMANCE MONITORING ---
Found out 5 web pages to analyze.
Analyzing site1.kinsta.cloud... Completed.
Analyzing site2.kinsta.cloud... Completed.
Analyzing site3.kinsta.cloud... Completed.
Analyzing example.com... PSI Error.
Analyzing site5.kinsta.cloud... Completed.
--- MONITORING COMPLETED ---
Since the 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 beautiful similar to the following:

Awesome. You’ve merely created your automated monitoring system.
Now, it’s possible you’ll want to keep an eye on it to fit your explicit needs. For instance, for individuals who arrange a whole lot of consumer web pages, sending a Slack message for each and every web site could be inefficient.
You want to, however, prepare a state of affairs that assessments the web site’s normal score and sends a message to the Slack channel only if the price 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 prevailing score is strictly lower than our prohibit.
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 "Completed.n";
else {
echo "Ranking is best possible ($score). No alert sent.n";
}
Change your script, save the document, 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 novel name in your script, keep an eye on the command accordingly.
The terminal will have to now show a series of messages similar to the following:
--- STARTING FULL PERFORMANCE MONITORING ---
Found out 5 web pages to analyze.
Analyzing site1.kinsta.cloud... Ranking is best possible (100). No alert sent.
Analyzing site2.kinsta.cloud... Ranking is best possible (95). No alert sent.
Analyzing site3.kinsta.cloud... Ranking is best possible (100). No alert sent.
Analyzing example.com... Ranking below threshold. Sending Slack alert... Completed.
Analyzing site5.kinsta.cloud... Ranking below threshold. Sending Slack alert... Completed.
--- MONITORING COMPLETED ---
In Slack, you will download a message for each and every web site with an normal score below the 90 threshold.

That’s great, isn’t it? Alternatively you can optimize the process even further. Wouldn’t you prefer to save some a lot more time via running the script automatically at set sessions without having to get entry to your command-line software?
Certain, you guessed it. You need a cron process.
Automate the process the usage of a cron process
There are a selection of tactics to organize a cron process on Kinsta. Despite the fact that you can do it thru WordPress, Kinsta consumers can upload server cron jobs to each and every web site container.
To prepare a cron process on Kinsta, create a cron command and add it on your container’s crontab document by means of SSH.
For example, you should 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 each day at 10 AM./usr/bin/phpis the absolute path of the PHP interpreter on the server./www/yoursite_123/public/your-script.phpis the absolute path of the script. Be mindful 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 document. /www/yoursite_123/performance_monitor.logindicates the document by which all text published throughout the script may also be saved.- The
2>&1command instructs the server to direct errors to the identical document.
We will now not discuss cron directions in more component proper right here. You’ll be able to visit the documentation from The Open Team or use a crontab software, an identical to Crontab Generator or Cronitor.
After building your cron command, you wish to have in an effort to upload it on your web site container. You’ll be able to each ask our give a boost to group of workers to try 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. Choose “nano” in the event you don’t seem to be certain.
Throughout the editor, paste your command at the end of the document. Save the document and return to the command line. You will have to 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 in your consumer web pages 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. For instance, you should 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’ web pages is only the start. Integrating the Kinsta API along side your group of workers’s day by day apparatus can turn into your corporate’s operations via eliminating information web site regulate and maintenance tasks, improving efficiency, and decreasing working prices. You’ll moreover enhance provider prime quality, reduce provide cases, and ensure the best possible enjoy in your customers.
The Kinsta API permits you to automate more than a few duties, along with 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 speedy and easy, allowing you to scale with self trust.
Able to take your corporate to the next stage? 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 appeared first on Kinsta®.





0 Comments