For modern corporations, a prime quality, consistent reporting gadget is essential for maintaining shopper believe and development long-term loyalty. A clear, informative report means that you can monitor product sales inclinations, expose advertising and marketing marketing campaign effectiveness, calculate return on investment (ROI), and much more.
On the other hand, for an corporate managing dozens or even plenty of internet sites, generating the ones periodic research can turn into a vital bottleneck, compromising the scalability of your operations.
That is why optimizing and automating wisdom retrieval is crucial. It restores efficiency and frees up your team of workers to be aware of high-value movements—like developing new projects.
In this article, you’ll discover ways to leverage the Kinsta API to automatically fetch your web web hosting wisdom and generate strategic research with the power of AI.
Can you scale your reporting gadget? Be told on.
Gaining access to Kinsta Analytics by means of MyKinsta and Kinsta API
Kinsta shoppers have get admission to to a wealth of data all over the MyKinsta internet hosting dashboard. You’ll have the ability to get admission to your plan wisdom inside the Analytics phase of your dashboard.

The Analytics internet web page is divided into a variety of tabs, every focusing on a decided on facet of your internet web site’s activity:
- Plan usage: Presentations your plan’s helpful useful resource consumption, every cumulatively and broken down by means of particular person internet web site.
- Best possible requests: Allows you to identify the primary requests in your internet web site, labeled by means of bandwidth and views.
- Cache: Provides a breakdown of cache usage, in conjunction with Cache breakdown, Server cache portions, and Server cache bypasses.
- CDN & edge: Supplies wisdom on CDN bandwidth consumption, Edge cache bandwidth, and lists of the easiest files served from the CDN cache.
- Dispersion: Shows the percentage of visits from desktop, tablet, and mobile.
- Potency: Contains rather numerous potency metrics harking back to Average PHP + MySQL response time, PHP throughput, PHP thread limit, and further.
- Response: Provides statistics on response codes, in conjunction with an extensive breakdown of error codes.
- Geo & IP: Presentations lists of the Best possible Global places, Best possible Cities, and Best possible Shopper IPs from which requests in your internet web site originate.
You’ll have the ability to get admission to the ones equivalent analytics on the internet web site level by means of navigating to Internet sites > sitename > Analytics.

Kinsta Analytics provides a staggering dataset; simply navigating your MyKinsta dashboard gives you an overly clear symbol of your internet web site’s helpful useful resource consumption, efficiency, and serve as. You’ll know exactly the position most requests come from and which ones devour necessarily probably the most property.
Blended with our Kinsta APM instrument, Kinsta Analytics means that you can optimize the potency of your WordPress internet sites.
What no longer everyone knows is that Kinsta Analytics wisdom may be to be had by means of the Kinsta API. This permits you to programmatically retrieve wisdom and assemble web web hosting metrics, which you’ll have the ability to then use to generate automatic research to share in conjunction with your clients.
Let’s uncover the Kinsta API endpoints.
The Analytics endpoint of the Kinsta API
With the Analytics endpoint of the Kinsta API, you’ll have the ability to get admission to raw wisdom in your internet web site’s helpful useful resource usage and neatly being.
- Visits utilization, server bandwidth utilization, and CDN bandwidth utilization: The ones metrics practice your helpful useful resource usage relative in your web web hosting plan during the existing billing period.
- Visits: Provides all the selection of visits to a given environment within a specified time period.
- Disk area: Provides all the disk space used by a given environment over a specified time period.
- Server bandwidth: Provides the bandwidth fed on by means of a given environment over a specified time period.
- CDN bandwidth: Provides the CDN bandwidth fed on by means of a given environment over a specified time period.
- Best International locations: Provides an inventory of the main global places from which requests to the internet web site originate within a specified time period.
- Best Towns: Provides an inventory of the main cities from which requests to the internet web site originated during a specified time period.
- Best Consumer IPs: Provides an inventory of the main shopper IP addresses from which requests to the internet web site originated during a specified time period.
- Talk over with Dispersion: It provides wisdom on the distribution of visits all over desktop, tablet, and mobile devices over a specified time period.
- Reaction Code Breakdown: Provides a breakdown of the HTTP status codes returned by means of the server within a specified time period.
Underneath are some examples of the way to use the analytics endpoint.
Visits
The following request provides all the selection of visits in your internet web site and the selection of unique IP addresses that have accessed it inside the ultimate 30 days:
https://api.kinsta.com/v2/internet sites/environments/{KINSTA_ENV_ID}/analytics/visits?time_span=30_days&company_id={KINSTA_COMPANY_ID}
The response shall be structured as follows:
{
"analytics": {
"analytics_response": {
"key": "uniqueip",
"wisdom": [
{
"name": "uniqueip",
"total": 1000,
"dataset": [
{
"key": "2025-10-28T00:00:00.000Z",
"value": "1000"
},
{
"key": "2025-10-28T00:00:00.000Z",
"value": "900"
},
{
"key": "2025-10-28T00:00:00.000Z",
"value": "820"
},
...
]
}
]
}
}
}
Bandwidth
The following example shows the way to query the Kinsta API to retrieve the server’s bandwidth usage all over the final 30 days:
https://api.kinsta.com/v2/internet sites/environments/{KINSTA_ENV_ID}/analytics/bandwidth?time_span=30_days&company_id={KINSTA_COMPANY_ID}
The response from the Kinsta server provides the day by day bandwidth usage for the former 30 days:
{
"analytics": {
"analytics_response": {
"key": "bandwidth",
"wisdom": [
{
"name": "bandwidth",
"total": 1000,
"dataset": [
{
"key": "2026-03-11T00:00:00.000Z",
"value": "37347250"
},
{
"key": "2026-03-12T00:00:00.000Z",
"value": "9276458"
},
...
]
}
]
}
}
}
CDN bandwidth
In this other example, we query the Kinsta API to resolve the CDN bandwidth usage for the former 7 days:
https://api.kinsta.com/v2/internet sites/environments/{KINSTA_ENV_ID}/analytics/cdn-bandwidth?time_span=7_days&company_id={KINSTA_COMPANY_ID}
The server will provide you with the next wisdom:
{
"analytics": {
"analytics_response": {
"key": "cdn-bandwidth",
"wisdom": [
{
"name": "cdn-bandwidth",
"total": 1000,
"dataset": [
{
"key": "2026-04-02T00:00:00.000Z",
"value": "753447"
},
{
"key": "2026-04-03T00:00:00.000Z",
"value": "16911"
},
...
]
}
]
}
}
}
You’ll be in a position to try it yourself by means of getting into your Kinsta API key (bearer token), environment ID, and company ID inside the API playground.

Now that you know how to get admission to your internet web site’s analytics wisdom on Kinsta, you’ll have the ability to use it to automate your operations. This moreover incorporates automating the reporting gadget.
The following sections will show you the way to automate your corporate’s reporting gadget using the Kinsta API. We will assemble a Python script and leverage GitHub Movements to automate the assemble and run. This will change into the raw wisdom returned by means of the API into tables and charts, and query Google AI to generate a final report.
It’s time to get your arms dirty.
Assemble an automated reporting gadget using the Kinsta API and Google AI
Our purpose is to create an automated report that is generated at explicit intervals. The gadget will query the Kinsta API to retrieve wisdom on visits, server bandwidth, and CDN bandwidth. This data will then be used to create charts and tables in a PDF file. As part of this process, the information shall be sent to the Gemini API to offer an analysis of the extracted wisdom, which is in a position to then be integrated inside the report.

Setting up the project on GitHub
On the GitHub homepage, click on at the fairway New button to create a brand spanking new project. Once you have an empty project, go to Settings > Secrets and techniques and methods and variables > Actions and add the secrets and techniques and methods confirmed inside the following image.

Storing your API keys and IDs in GitHub Secrets and techniques and methods helps to keep them inaccessible to someone and helps make sure your code remains secure.
GEMINI_API_KEY
You’ll have the ability to generate a Google AI API key inside the Google AI Studio dashboard. Please visit the Google AI documentation for more information.
KINSTA_API-KEY
Next, apply the instructions in our article to generate a Kinsta API key.
KINSTA_COMPANY_ID, KINSTA_ENV_ID, KINSTA_SITE_ID
You’ll have the ability to to find the Site ID, Atmosphere ID, and Company ID under Internet sites > sitename > Knowledge on your MyKinsta dashboard.

Now let’s switch at once to the project files.
Required libraries and GitHub Actions configuration
Throughout the root list of your GitHub project, create a file named must haves.txt and add the following:
google-genai
requests
matplotlib
fpdf2
This file lists the portions required for your project.
google-genai: This is Google’s library for interacting with Gemini models.requests: A library for making HTTP requests. In this project, it’ll be used to send HTTP requests to the Kinsta API.matplotlib: A Python library for growing graphs and visualizing knowledge.fpdf2: This can be a library that allows you to generate PDF recordsdata.
Next, create a file named .github/workflows/generate_report.yml with the following code:
determine: Generate Kinsta Analytics Report
on:
push:
branches: [main]
workflow_dispatch:
jobs:
build-and-run:
runs-on: ubuntu-latest
steps:
- determine: Checkout Repository
uses: actions/checkout@v4
- determine: Organize Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
- determine: Arrange dependencies
run: |
python -m pip arrange --upgrade pip
pip arrange -r must haves.txt
- determine: Run Report Script
env:
KINSTA_API_KEY: ${{ secrets and techniques and methods.KINSTA_API_KEY }}
KINSTA_ENV_ID: ${{ secrets and techniques and methods.KINSTA_ENV_ID }}
KINSTA_SITE_ID: ${{ secrets and techniques and methods.KINSTA_SITE_ID }}
KINSTA_COMPANY_ID: ${{ secrets and techniques and methods.KINSTA_COMPANY_ID }}
GEMINI_API_KEY: ${{ secrets and techniques and methods.GEMINI_API_KEY }}
run: python number one.py
- determine: Upload Report
uses: actions/upload-artifact@v4
with:
determine: Kinsta-Advanced-Report
path: "*.pdf"
GitHub uses this report back to automatically run your code by means of GitHub Actions. Let’s take a better look:
determine: Generate Kinsta Analytics Report
on:
push:
branches: [main]
workflow_dispatch:
determine: The determine of your project as it seems that inside the Actions tab on GitHub.on: Determines when to purpose the workflow.push: The workflow runs every time you push a code change to the main division.workflow_dispatch: Allows you to run the workflow manually.
jobs:
build-and-run:
runs-on: ubuntu-latest
jobs: The start of the tasks to be performed.build-and-run: An arbitrary determine that identifies a decided on collection of actions.runs-on: Specifies the gadget on which the workflow will have to run.ubuntu-latest: Devices the newest version of Ubuntu Linux.
steps:
- determine: Checkout Repository
uses: actions/checkout@v4
- determine: Organize Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
steps: The collection of operations to be performed.determine: The determine of the operation to be performeduses: The pre-configured GitHub module (Movement)
- determine: Arrange dependencies
run: |
python -m pip arrange --upgrade pip
pip arrange -r must haves.txt
python -m pip arrange --upgrade pip: Updates pip (the Python bundle supervisor) to the newest available version.pip arrange -r must haves.txt: Reads themust haves.txtfile and installs the packages listed in it.
- determine: Run Report Script
env:
KINSTA_API_KEY: ${{ secrets and techniques and methods.KINSTA_API_KEY }}
KINSTA_ENV_ID: ${{ secrets and techniques and methods.KINSTA_ENV_ID }}
KINSTA_SITE_ID: ${{ secrets and techniques and methods.KINSTA_SITE_ID }}
KINSTA_COMPANY_ID: ${{ secrets and techniques and methods.KINSTA_COMPANY_ID }}
GEMINI_API_KEY: ${{ secrets and techniques and methods.GEMINI_API_KEY }}
run: python number one.py
env: Retrieves environment variable values from GitHub Secrets and techniques and methods.run: python number one.py: Launches the Python interpreter and runs thenumber one.pyfile.
- determine: Upload Report
uses: actions/upload-artifact@v4
with:
determine: Kinsta-Advanced-Report
path: "*.pdf"
uses: actions/upload-artifact@v4: Uses the GitHub movement to regulate artifacts, a file or folder generated while the script is operating.with: Devices the configuration parameters.
The configuration of your automation project is complete. Now it’s time to create the Python scripts.
Querying the Kinsta API programmatically
Once you have completed the setup, navigate to the root list of your GitHub project and create a brand spanking new file named kinsta_utils.py with the following code:
import requests
import os
KINSTA_API_KEY = os.getenv("KINSTA_API_KEY")
KINSTA_SITE_ID = os.getenv("KINSTA_SITE_ID")
KINSTA_ENV_ID = os.getenv("KINSTA_ENV_ID")
KINSTA_COMPANY_ID = os.getenv("KINSTA_COMPANY_ID")
BASE_URL = f"https://api.kinsta.com/v2/internet sites/environments/{KINSTA_ENV_ID}/analytics"
def get_headers():
return {"Authorization": f"Bearer {KINSTA_API_KEY}"}
- The principle two
importstatements load the standard library for making HTTP requests and the module for interacting with the operating gadget (os). - The next 4 traces (
os.getenv) retrieve your credentials from GitHub Secrets and techniques and methods. BASE_URLdefines the main endpoint of the Kinsta API used by the script.- The
get_headersfunction generates the Authorization Header, which is in a position to include the Kinsta API key.
Next, create a helper function that converts the raw wisdom returned by means of the API into megabytes.
def format_bytes_to_mb(bytes_value):
"""Converts raw bytes from API to human-readable Megabytes."""
check out:
# Usual conversion to MB
# return round(int(bytes_value) / (1024 * 1024), 2)
# Decimal standard (used in MyKinsta dashboard)
return round(int(bytes_value) / 1_000_000, 2)
except (ValueError, TypeError):
return 0
- This code provides two alternatives. The principle uses the binary standard (
1024 x 1024), and the second uses the decimal standard. Dividing by means of1_000_000promises that the amount on your PDF report fits the amount that your clients would see in MyKinsta Analytics.
The following function queries the Kinsta API and returns a selection of raw wisdom:
def fetch_kinsta_metric(endpoint, start_date, end_date):
url = f"{BASE_URL}/{endpoint}"
params = {
"company_id": KINSTA_COMPANY_ID,
"from": f"{start_date}T00:00:00.000Z",
"to": f"{end_date}T23:59:59.000Z"
}
check out:
response = requests.get(url, headers=get_headers(), params=params)
if response.status_code == 200:
data_node = response.json()['analytics']['analytics_response']['data'][0]
common = data_node.get('common', 0)
dataset = data_node.get('dataset', [])[:7]
return common, dataset
except Exception as e:
print(f"Error fetching {endpoint}: {e}")
return 0, []
- The
fetch_kinsta_metricfunction takes 3 arguments:endpoint,start_date, andend_date. The ones are used to construct the request URL. The endpoint can bevisits,bandwidth, orcdn-bandwidth. - The
paramsarray stores the request parameters. - Kinsta’s response is a nested JSON object (
data_node) which supplies the aggregated values for the period (common) and an inventory of day by day values (dataset).
The overall function inside the kinsta_utils.py file retrieves the internet web site determine.
def fetch_site_name():
url = f"https://api.kinsta.com/v2/internet sites/{KINSTA_SITE_ID}"
check out:
response = requests.get(url, headers=get_headers())
if response.status_code == 200:
wisdom = response.json()
site_data = wisdom.get('internet web site', {})
site_label = site_data.get('display_name', 'Unknown Site')
env_label = "Unknown Env"
envs = site_data.get('environments', [])
for env in envs:
if env.get('id') == KINSTA_ENV_ID:
env_label = env.get('display_name')
wreck
return f"{site_label} ({env_label})"
else:
print(f"Kinsta API Error: {response.status_code} - {response.text}")
except Exception as e:
print(f"Error fetching internet web site determine: {e}")
return "Unknown Site"
This code will have to be self-explanatory. Please visit the API Reference for details on the websites endpoint.
Now all that’s left is to organize the workflow.
Automate the workflow with Python and Gemini
The general file you wish to have to create is the engine for your device. However inside the root list of your GitHub project, create a file number one.py. To start out out, add the following code:
import os
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from google.genai import Shopper
from fpdf import FPDF, XPos, YPos
from datetime import datetime, timedelta
from kinsta_utils import fetch_kinsta_metric, format_bytes_to_mb, fetch_site_name
REPORT_LANG = "en"
MODEL_ID = "gemini-2.5-flash"
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
shopper = Shopper(api_key=GEMINI_API_KEY)
at the moment = datetime.now()
curr_end_dt = at the moment - timedelta(days=1)
curr_start_dt = at the moment - timedelta(days=7)
prev_end_dt = at the moment - timedelta(days=8)
prev_start_dt = at the moment - timedelta(days=14)
CURR_RANGE = f"{curr_start_dt.strftime('%b %d')} - {curr_end_dt.strftime('%b %d')}"
PREV_RANGE = f"{prev_start_dt.strftime('%b %d')} - {prev_end_dt.strftime('%b %d')}"
DATES = [
prev_start_dt.strftime("%Y-%m-%d"),
prev_end_dt.strftime("%Y-%m-%d"),
curr_start_dt.strftime("%Y-%m-%d"),
curr_end_dt.strftime("%Y-%m-%d")
]
CURR_DAYS_LABELS = [(curr_start_dt + timedelta(days=i)).strftime("%d %a") for i in range(7)]
PREV_DAYS_LABELS = [(prev_start_dt + timedelta(days=i)).strftime("%d %a") for i in range(7)]
X_AXIS_LABELS = [(curr_start_dt + timedelta(days=i)).strftime("%d") for i in range(7)]
This is how the script is set up:
- The
importstatements load the necessary libraries, andmatplotlib.use('Agg')instructs Python to generate the plots and keep them in memory. - The following block gadgets the language (
en) and the manner (gemini-2.5-flash), then initializes the Google shopper. - Next, it defines time house home windows to test values from the general seven days with those from the previous seven days.
- In any case, it gadgets the labels for tables and graphs.
Your next step is to stipulate a KinstaReport elegance for generating report pages using the FPDF library:
elegance KinstaReport(FPDF):
def __init__(self, site_name="Unknown Site"):
super().__init__()
self.site_name = site_name
def header(self):
self.set_font("Helvetica", "B", 8)
self.set_text_color(150)
# Site determine
self.cell(100, 10, f"Site: {self.site_name}", align="L")
# Date generated
self.cell(0, 10, f"Kinsta Analytics Report | Generated: {datetime.now().strftime('%Y-%m-%d')}",
align="R", new_x=XPos.LMARGIN, new_y=YPos.NEXT)
def add_metric_page(self, determine, chart_path, prev_vals, curr_vals, unit=""):
self.add_page()
# Internet web page determine
self.set_font("Helvetica", "B", 24)
self.set_text_color(83, 51, 237)
self.cell(0, 15, determine, align="C", new_x=XPos.LMARGIN, new_y=YPos.NEXT)
# Subtitle
self.set_font("Helvetica", "I", 10)
self.set_text_color(120)
self.cell(0, 5, f"Comparison: {CURR_RANGE} vs {PREV_RANGE}", align="C", new_x=XPos.LMARGIN, new_y=YPos.NEXT)
self.image(chart_path, x=10, y=42, w=190)
# Wisdom tables
self.set_y(150)
self.set_font("Helvetica", "B", 10)
self.set_fill_color(245, 245, 255)
self.set_text_color(83, 51, 237)
# Table header
col1, col2 = 35, 60
self.cell(col1, 10, " Day (Prev)", border=1, align='C', fill=True, new_x=XPos.RIGHT, new_y=YPos.TOP)
self.cell(col2, 10, f"Value {unit}", border=1, align='C', fill=True, new_x=XPos.RIGHT, new_y=YPos.TOP)
self.cell(col1, 10, " Day (Curr)", border=1, align='C', fill=True, new_x=XPos.RIGHT, new_y=YPos.TOP)
self.cell(col2, 10, f"Value {unit}", border=1, align='C', fill=True, new_x=XPos.LMARGIN, new_y=YPos.NEXT)
self.set_font("Helvetica", "", 10)
self.set_text_color(50)
for i in range(7):
# Zebra striping
fill = (i % 2 == 0)
if fill: self.set_fill_color(250, 250, 250)
else: self.set_fill_color(255, 255, 255)
self.cell(col1, 9, f" {PREV_DAYS_LABELS[i]}", border=1, align='C', fill=fill, new_x=XPos.RIGHT, new_y=YPos.TOP)
self.cell(col2, 9, f" {prev_vals[i]}", border=1, align='C', fill=fill, new_x=XPos.RIGHT, new_y=YPos.TOP)
self.cell(col1, 9, f" {CURR_DAYS_LABELS[i]}", border=1, align='C', fill=fill, new_x=XPos.RIGHT, new_y=YPos.TOP)
self.cell(col2, 9, f" {curr_vals[i]}", border=1, align='C', fill=fill, new_x=XPos.LMARGIN, new_y=YPos.NEXT)
We won’t go into a great deal of part about this code. For more information on the FPDF library, please visit the online property:
Next, define a function generated_chart. This function converts the raw wisdom received from Kinsta into charts.
def generate_chart(labels, curr, prev, determine, ylabel, filename, is_bar=False):
plt.resolve(figsize=(10, 5), dpi=100)
ax = plt.gca()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_color('#dddddd')
ax.spines['bottom'].set_color('#dddddd')
if is_bar:
# Bar Chart for bandwidth
bars = plt.bar(labels, curr, color='#00c4b4', alpha=0.6, label='Provide Length', width=0.6)
# Add labels above the bars
for bar in bars:
most sensible = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2., most sensible + 0.02, f'{most sensible}', ha='center', va='bottom', fontsize=8, color='#00a194')
else:
# Line chart for visits
plt.plot(labels, curr, color='#5333ed', marker='o', markersize=6, linewidth=3, label='Provide', zorder=3)
plt.plot(labels, prev, color='#a1a1a1', linestyle='--', marker='x', markersize=5, linewidth=1.5, label='Previous', alpha=0.6)
plt.fill_between(labels, curr, color='#5333ed', alpha=0.1)
plt.determine(determine, fontsize=14, pad=20, color='#333333', fontweight='bold')
plt.ylabel(ylabel, color='#666666')
plt.xlabel("Day of Month", color='#666666')
plt.legend(frameon=False, loc='upper correct')
plt.grid(axis='y', linestyle='--', alpha=0.3)
plt.tight_layout()
plt.savefig(filename)
plt.close()
This function uses the Matplotlib library to grow to be the information extracted from Kinsta into charts for inclusion inside the PDF report. For more information on using the Matplotlib library, please visit the online documentation:
In any case, add the function that combines all the parts we’ve described thus far.
def number one():
site_display_name = fetch_site_name()
metrics = {
"visits": {"determine": "Site Visits", "unit": ""},
"bandwidth": {"determine": "Server Bandwidth", "unit": "(MB)"},
"cdn-bandwidth": {"determine": "CDN Bandwidth", "unit": "(MB)"}
}
report_data = {}
for key in metrics:
_, data_curr = fetch_kinsta_metric(key, DATES[2], DATES[3])
_, data_prev = fetch_kinsta_metric(key, DATES[0], DATES[1])
curr_vals = []
prev_vals = []
for i in range(7):
c = flow(data_curr[i]['value']) if i < len(data_curr) else 0
p = flow(data_prev[i]['value']) if i < len(data_prev) else 0
if "bandwidth" in key:
curr_vals.append(format_bytes_to_mb(c))
prev_vals.append(format_bytes_to_mb(p))
else:
curr_vals.append(int(c))
prev_vals.append(int(p))
report_data[key] = {"curr": curr_vals, "prev": prev_vals}
pdf = KinstaReport(site_name=site_display_name)
for key, knowledge in metrics.items():
chart_file = f"{key}_chart.png"
generate_chart(X_AXIS_LABELS, report_data[key]["curr"], report_data[key]["prev"],
f"{knowledge['title']} Tendencies", "Devices", chart_file, is_bar=("bandwidth" in key))
pdf.add_metric_page(knowledge["title"], chart_file, report_data[key]["prev"], report_data[key]["curr"], knowledge["unit"])
# Government Summary
pdf.add_page()
pdf.set_font("Helvetica", "B", 20)
pdf.set_text_color(83, 51, 237)
pdf.cell(0, 15, "Government Summary", align="C", new_x=XPos.LMARGIN, new_y=YPos.NEXT)
curr_visits = sum(report_data['visits']['curr'])
prev_visits = sum(report_data['visits']['prev'])
curr_bw = sum(report_data['bandwidth']['curr'])
prev_bw = sum(report_data['bandwidth']['prev'])
check out:
summary_prompt = (
f"Analyze Kinsta potency for internet web site {site_display_name}. "
f"Provide Length ({CURR_RANGE}): {curr_visits} visits, {curr_bw:.2f}MB server bandwidth. "
f"Previous Length ({PREV_RANGE}): {prev_visits} visits, {prev_bw:.2f}MB server bandwidth. "
f"Read about the ones categories and identify inclinations. Language: {REPORT_LANG}. Max 4 sentences."
)
response = shopper.models.generate_content(taste=MODEL_ID, contents=summary_prompt)
summary = response.text
except Exception as e:
summary = f"Analytical insights unavailable. Error: {str(e)}"
pdf.set_y(40)
pdf.set_font("Helvetica", "", 12)
pdf.set_text_color(0)
pdf.multi_cell(0, 8, summary)
report_filename = f"Kinsta_Report_{datetime.now().strftime('%Y-%m-%d')}.pdf"
pdf.output(report_filename)
print(f"Report generated: {report_filename}")
if __name__ == "__main__":
number one()
That’s what this code does:
- The
forloop iterates all over themetricsarray and queries the Kinsta API two instances: once for the existing week and once for the previous week. - If the information relates to bandwidth, the
format_bytes_to_mb()function converts the raw wisdom into MB. - The
report_data()function stores the retrieved wisdom. KinstaReportthen creates a PDF for every internet web site.- The next
forloop generates PNG photos for the charts and creates a brand spanking new internet web page for every metric. - The next phase generates the manager summary, calculates all the selection of visits and common megabytes for the period, and sends a dynamic beneficial to Gemini 2.5 Flash. In any case, the response is used to complete the general internet web page of the PDF.
- The script saves the report with a file determine that incorporates the existing date.
- * The overall scenario promises the process runs best when the script is carried out as the main program.
It’s time to build and run your device.
Retrieving the Artifact
You are able to now run your device. In your GitHub project internet web page, click on at the Actions tab. Seek for the determine of your movement inside the menu on the left (in our example, this is Generate Kinsta Analytics Report, as specified on your generate_report.yml file).

Next, click on at the Run workflow menu at the correct, then click on at the fairway Run workflow button (best the main division is in recent times available).

The next internet web page shows the existing workflow. Click on on on it to view the document of ongoing operations.

The Run Report Script phase provides an inventory of the operations performed, while the Upload Report phase provides the artifact download URL. Click on in this link to acquire your report in PDF format.

You’ll to find the identical link inside the Artifacts phase, at the bottom of the workflow’s Summary internet web page.

The pictures underneath show the complete report, in conjunction with the Government Summary generated by means of Google AI.


Next steps: One of the best ways to support scalability and automate provide
This is just a taste of what the Kinsta API can do when mixed with advanced automation equipment like GitHub Actions. AI integration takes it further, transforming raw numbers into deep-dive research in a position to be shared in conjunction with your clients.
You are able to further support your reporting in a large number of techniques:
- You are able to configure your device by means of together with a line to the YAML file (
schedule: '0 9 * * 1') to generate the report every Monday morning at 9:00 AM. - You could need to mix a library like
smtplibor a supplier like SendGrid to send the report in an instant in your shopper. - If you are an corporate with dozens or even plenty of internet sites, you wish to have to put in force a loop that iterates over an inventory of internet web site IDs to generate your whole research in a single run.
- You are able to further enrich your report’s content material subject material by means of using the Kinsta API to retrieve geographic wisdom, HTTP code breakdowns, server logs, and some other wisdom you wish to have to include. By means of analyzing this data, the AI can identify attack makes an try (4xx codes) or guests spikes from surprising spaces.
- You are able to fine-tune your beneficial to get additional detailed and entire AI responses.
- You are able to customize the PDF template in conjunction with your corporate’s and your shopper’s logos.
Automated reporting reduces your team of workers’s workload, and the consistency and precision it provides reinforce your clients’ believe and loyalty.
Need to get began automating your shopper reporting straight away? Subscribe to the plan that most nearly fits your needs and get began development with the Kinsta API at the moment.
The submit Automate consumer reporting with Kinsta API and Google AI gave the impression first on Kinsta®.


0 Comments