A small PHP JSON API endpoint

One PHP file that handles GET, POST and DELETE safely.

AJAX · A small PHP JSON API endpointAdvanced
// api/items.php  (PHP shown as comments)
// <?php
// declare(strict_types=1);
// header('Content-Type: application/json; charset=utf-8');
// header('Cache-Control: no-store');
//
// function out(int $code, array $data): never { http_response_code($code); echo json_encode($data); exit; }
//
// $method = $_SERVER['REQUEST_METHOD'];
// if ($method === 'GET')  out(200, ['ok' => true, 'items' => $pdo->query('SELECT id,name FROM items')->fetchAll()]);
// if ($method === 'POST') {
//     $in = json_decode(file_get_contents('php://input'), true) ?: [];
//     $name = trim((string)($in['name'] ?? ''));
//     if ($name === '' || mb_strlen($name) > 100) out(422, ['ok' => false, 'error' => 'Invalid name']);
//     $pdo->prepare('INSERT INTO items(name) VALUES(?)')->execute([$name]);
//     out(201, ['ok' => true, 'id' => (int)$pdo->lastInsertId()]);
// }
// out(405, ['ok' => false, 'error' => 'Method not allowed']);

fetch('/api/items.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Pen' }) });
phpapirestjsonmethod