Skip to content
AgileLogics
5 min read

Building a REST API in Depth

Prerequisites: Security fundamentals

A real REST API layers together several lessons from this course: routing (via a framework, or $_SERVER['REQUEST_URI'] in plain PHP), JSON encoding/decoding, PDO for persistence, proper HTTP status codes, and input validation.

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

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

if ($method === 'GET' && preg_match('#^/users/(\d+)$#', $path, $matches)) {
    $user = findUser((int) $matches[1]);
    if (! $user) {
        http_response_code(404);
        echo json_encode(['error' => 'User not found']);
        exit;
    }
    echo json_encode($user);
}

In practice, a framework's router (next two lessons) handles all of this path-matching and status-code plumbing for you — this plain-PHP version exists to show exactly what a framework is doing underneath.