Architecting a Clean REST Endpoint
A production REST API requires consistent HTTP response statuses, appropriate content headers, and unified error handling:
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=UTF-8');
header('X-Content-Type-Options: nosniff');
$method = $_SERVER['REQUEST_METHOD'];
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
if ($method === 'GET' && $uri === '/api/v1/calculators') {
$stmt = $pdo->query('SELECT id, name, slug, category FROM calculators WHERE is_active = 1');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
http_response_code(200);
echo json_encode(['status' => 'success', 'data' => $results], JSON_THROW_ON_ERROR);
exit;
}
http_response_code(404);
echo json_encode(['status' => 'error', 'message' => 'Resource not found'], JSON_THROW_ON_ERROR);