Creating API Endpoints for Specific Data
In this tutorial, you will create multiple APIFocused endpoints that return differentthe typessmallest ofuseful data.result for a particular user need. This tutorial adds filtered and summary endpoints using PDO and fictional records.
This
Endpoint approachfor isone commonly used in modern web applications.
Why Create Multiple Endpoints?severity
Your current API returns all records:
api_events.php
This works, but many applications need smaller, more focused datasets.
For example:
api_events.php
api_critical_events.php
api_statistics.php
Each endpoint has a specific purpose.
Create a Critical Events API
Create:
api_critical_events.api/events-by-severity.php
Add::
<?php
$conndeclare(strict_types=1);
=require new__DIR__ mysqli(. "localhost",'/../includes/database.php';
"root",header('Content-Type: "",application/json; "project_db"
charset=utf-8');
header('Cache-Control: "Content-Type: application/json"
no-store');
$queryallowed = "['low', 'medium', 'high', 'critical'];
$severity = strtolower(trim($_GET['severity'] ?? ''));
if (!in_array($severity, $allowed, true)) {
http_response_code(400);
echo json_encode([
'ok' => false,
'error' => 'Choose low, medium, high or critical.'
]);
exit;
}
$statement = $pdo->prepare(
'SELECT
*event_id,
event_timestamp,
device_id,
room,
event_type,
severity
FROM security_events
WHERE severity = 'critical':severity
"ORDER BY event_timestamp DESC
LIMIT 100'
);
$resultstatement->execute(['severity' => $conn->query($query)severity]);
$events = []$statement->fetchAll();
while (
$row =
$result->fetch_assoc()
) {
$events[] = $row;
}
echo json_encode([
'ok' => true,
'filter' => ['severity' => $events,severity],
JSON_PRETTY_PRINT'count' => count($events),
'events' => $events
]);
?>
Test theit Endpointwith
Open:a fictional category:
http://localhost/api-demo/api_critical_events.phpproject/api/events-by-severity.php?severity=high
YouThe shouldallow-list onlyrejects seeunexpected criticalvalues events.and the prepared statement keeps the supplied value separate from the SQL.
Endpoint
summary
ScreenshotforPlaceholder
Insert screenshot showing critical event results.
Create a Statistics APItotals
Create:
api_statistics.api/event-summary.php
Add::
<?php
$conndeclare(strict_types=1);
=require new__DIR__ mysqli(. "localhost",'/../includes/database.php';
"root",header('Content-Type: "",application/json; "project_db"
charset=utf-8');
header('Cache-Control: "Content-Type: application/json"
no-store');
$statistics = [
"total_events" => 0,
"critical_events" => 0,
"high_events" => 0
];
$resultstatement = $conn-pdo->query(
"'SELECT COUNT(*) AS total
FROM security_events"
);
$statistics["total_events"] =
$result->fetch_assoc()["total"];
$result =
$conn->query(
"SELECTseverity, COUNT(*) AS total
FROM security_events
WHEREGROUP severity='critical'"BY severity
ORDER BY severity'
);
$statistics["critical_events"rows = $statement->fetchAll();
$summary = [];
foreach ($rows as $row) {
$summary[] = [
'severity' => $result-row['severity'],
'total' =>fetch_assoc()["total" (int) $row['total']
];
$result =
$conn->query(
"SELECT COUNT(*) AS total
FROM security_events
WHERE severity='high'"
);
$statistics["high_events"] =
$result->fetch_assoc()["total"];}
echo json_encode([
'ok' => true,
'summary' => $statistics,summary
JSON_PRETTY_PRINT
]);
?>
Test the Statistics Endpoint
Open:
http://localhost/api-demo/api_statistics.php
Example:
{
"total_events": 3,
"critical_events": 1,
"high_events": 1
}
Read the Statistics API with JavaScript
Create:
dashboard.html
Add:
<!DOCTYPE html>
<html>
<head>
<title>Dashboard</title>
</head>
<body>
<h1>Security Dashboard</h1>
<div id="output"></div>
<script>
fetch("api_statistics.php")
.then(response => response.json())
.then(data => {
document.getElementById(
"output"
).innerHTML = `
<p>
Total Events:
${data.total_events}
</p>
<p>
Critical Events:
${data.critical_events}
</p>
<p>
High Events:
${data.high_events}
</p>
`;
});
</script>
</body>
</html>
Common Endpoint Examples
Many real systems use endpoints such as:
/api/users
/api/products
/api/orders
/api/messages
/api/statistics
EachThis endpoint returns processed information rather than every event record. It can support an accessible table or chart.
Choose endpoints from user needs
Useful endpoints might answer:
Avoid creating many endpoints that expose the same unnecessary fields.
Check
information
Summary
or Youcredentials noware have:
api_events.phpAll demonstration Returnsrecords allare events.
api_critical_events.php
Returns only critical events.
api_statistics.php
Returns dashboard statistics.
This approach keeps APIs organised and makes applications easier to maintain.