Lesson 2 of 7
API Router - Request Parsing & Dispatch
A REST API router matches method + path to a controller action, extracts URL parameters, and dispatches. Unlike HTML routers, an API router must handle OPTIONS for CORS preflight, return JSON for all errors (including 404/405), and always set Content-Type: application/json.
REST API Router Implementation
<?php
declare(strict_types=1);
class ApiRouter {
private array $routes = [];
public function get(string $path, callable $handler): void { $this->add("GET", $path, $handler); }
public function post(string $path, callable $handler): void { $this->add("POST", $path, $handler); }
public function put(string $path, callable $handler): void { $this->add("PUT", $path, $handler); }
public function patch(string $path, callable $handler): void { $this->add("PATCH", $path, $handler); }
public function delete(string $path, callable $handler): void { $this->add("DELETE", $path, $handler); }
private function add(string $method, string $path, callable $handler): void {
// Convert /posts/{id}/comments/{cid} to regex
$pattern = preg_replace("/{([a-zA-Z_]+)}/", "(?P<$1>[^/]+)", $path);
$this->routes[] = [
"method" => $method,
"pattern" => "#^" . $pattern . "$#",
"handler" => $handler,
];
}
public function dispatch(): void {
// JSON for all responses - set globally
header("Content-Type: application/json; charset=UTF-8");
// CORS headers - adjust origins for production
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Key");
$method = $_SERVER["REQUEST_METHOD"];
$path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH) ?? "/";
$path = "/" . trim($path, "/");
// CORS preflight - browsers send OPTIONS before cross-origin requests
if ($method === "OPTIONS") {
http_response_code(204);
exit;
}
foreach ($this->routes as $route) {
if ($route["method"] !== $method) continue;
if (!preg_match($route["pattern"], $path, $matches)) continue;
// Extract named URL params: {id}, {slug}
$params = array_filter($matches, "is_string", ARRAY_FILTER_USE_KEY);
try {
$request = new ApiRequest($params);
$response = ($route["handler"])($request);
$response->send();
} catch (ValidationException $e) {
ApiResponse::error($e->errors, 422)->send();
} catch (NotFoundException $e) {
ApiResponse::error(["message" => $e->getMessage()], 404)->send();
} catch (AuthorizationException $e) {
ApiResponse::error(["message" => $e->getMessage()], 403)->send();
} catch (Throwable $e) {
error_log("API error: " . $e->getMessage() . "
" . $e->getTraceAsString());
ApiResponse::error(["message" => "Internal server error"], 500)->send();
}
return;
}
// No matching route
$methodMatches = array_filter($this->routes, fn($r) => preg_match($r["pattern"], $path));
if (!empty($methodMatches)) {
http_response_code(405);
echo json_encode(["success" => false, "error" => ["code" => "METHOD_NOT_ALLOWED", "message" => "Method not allowed"]]);
} else {
http_response_code(404);
echo json_encode(["success" => false, "error" => ["code" => "NOT_FOUND", "message" => "Endpoint not found"]]);
}
exit;
}
}
class ApiRequest {
private readonly array $body;
public readonly string $rawBody;
public function __construct(public readonly array $params = []) {
$this->rawBody = file_get_contents("php://input") ?? "";
$this->body = !empty($this->rawBody)
? (json_decode($this->rawBody, true, flags: JSON_THROW_ON_ERROR) ?? [])
: [];
}
public function param(string $key): ?string { return $this->params[$key] ?? null; }
public function body(string $key, mixed $default = null): mixed { return $this->body[$key] ?? $default; }
public function query(string $key, mixed $default = null): mixed { return $_GET[$key] ?? $default; }
public function header(string $name): string { return $_SERVER["HTTP_" . strtoupper(str_replace("-", "_", $name))] ?? ""; }
public function bearerToken(): ?string {
$auth = $this->header("Authorization");
if (str_starts_with($auth, "Bearer ")) return substr($auth, 7);
return null;
}
public function apiKey(): ?string { return $this->header("X-API-Key") ?: $this->query("api_key"); }
public function isJson(): bool { return str_contains($this->header("Content-Type"), "application/json"); }
}Quick Quiz
Tip
Tip
Practice API Router Request Parsing Dispatch in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for API Router - Request Parsing & Dispatch
Practice Task
Note
Practice Task - (1) Write a working example of API Router Request Parsing Dispatch from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with API Router Request Parsing Dispatch is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?