Back to Tutorials

Building REST APIs with Vanilla PHP

Simple PHP API

Learn how to build REST APIs using pure PHP without frameworks, giving you full control over your code.

Basic API Structure

// api.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

$method = $_SERVER['REQUEST_METHOD'];
$path = $_SERVER['PATH_INFO'] ?? '/';

switch ($method) {
    case 'GET':
        handleGet($path);
        break;
    case 'POST':
        handlePost($path);
        break;
}

function handleGet($path) {
    if ($path === '/users') {
        $db = getDB();
        $stmt = $db->query("SELECT * FROM users");
        $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($users);
    }
}

Best Practices

  • Use PDO for database access
  • Validate and sanitize all input
  • Use prepared statements
  • Set proper HTTP status codes
  • Handle errors gracefully