Building a REST API in Plain PHP Without a Framework

You don’t need Laravel or Symfony to build a working REST API — plain PHP with a front controller gets you surprisingly far for a small internal service.

header('Content-Type: application/json');

$method = $_SERVER['REQUEST_METHOD'];
$path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');

if ($method === 'GET' && $path === 'api/users') {
    $pdo = new PDO('mysql:host=localhost;dbname=app', 'user', 'pass');
    $users = $pdo->query('SELECT id, name FROM users')->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($users);
    exit;
}

if ($method === 'POST' && $path === 'api/users') {
    $body = json_decode(file_get_contents('php://input'), true);
    // validate and insert $body...
    http_response_code(201);
    echo json_encode(['status' => 'created']);
    exit;
}

http_response_code(404);
echo json_encode(['error' => 'Not found']);

For anything beyond a handful of endpoints, a routing library (or a real framework) pays for itself quickly — but this pattern is a genuinely reasonable choice for a small, self-contained internal API.