Lesson 7 of 7
Mini Project: Blog System - Part 9 (Complete REST API)
Wire together the complete Blog REST API - versioned router, authenticated endpoints, rate limiting, CRUD for posts, JWT concept documentation, and a public read endpoint with pagination and search. This is a production-ready API skeleton.
Blog Part 9 - Complete API Bootstrap
<?php
declare(strict_types=1);
// public/api.php - API entry point
require __DIR__ . "/../vendor/autoload.php";
use DotenvDotenv;
use AppBootstrapContainer;
$dotenv = Dotenv::createImmutable(__DIR__ . "/../");
$dotenv->load();
$container = new Container();
$postCtrl = $container->get(PostApiController::class);
$authCtrl = $container->get(AuthApiController::class);
$limiter = new RateLimitMiddleware($container->get(RateLimiterInterface::class), 60, 60);
$authMW = $container->get(ApiAuthMiddleware::class);
// Security headers for API
header("Content-Type: application/json; charset=UTF-8");
header("X-Content-Type-Options: nosniff");
header("Access-Control-Allow-Origin: " . ($_ENV["CORS_ORIGIN"] ?? "*"));
header("Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Key, X-RateLimit-Limit");
if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") { http_response_code(204); exit; }
// Global rate limit - all endpoints
$req = new ApiRequest();
$limiter->handle($req);
// ── Routes ────────────────────────────────────────────────────
$router = new VersionedApiRouter();
$v1 = $router->version("v1");
// Public - no auth required
$v1->get("/api/v1/posts", fn($r) => $postCtrl->index($r));
$v1->get("/api/v1/posts/{slug}", fn($r) => $postCtrl->show($r));
// Auth required
$v1->post("/api/v1/posts", fn($r) => $postCtrl->store($r));
$v1->put("/api/v1/posts/{id}", fn($r) => $postCtrl->update($r));
$v1->patch("/api/v1/posts/{id}", fn($r) => $postCtrl->patch($r));
$v1->delete("/api/v1/posts/{id}", fn($r) => $postCtrl->destroy($r));
// Post actions
$v1->post("/api/v1/posts/{id}/publish", fn($r) => $postCtrl->publish($r));
$v1->post("/api/v1/posts/{id}/archive", fn($r) => $postCtrl->archive($r));
// Auth endpoints (stricter rate limit applied inside controller)
$v1->post("/api/v1/auth/login", fn($r) => $authCtrl->login($r));
$v1->post("/api/v1/auth/logout", fn($r) => $authCtrl->logout($r));
$v1->get("/api/v1/auth/me", fn($r) => $authCtrl->me($r));
$v1->post("/api/v1/auth/tokens", fn($r) => $authCtrl->createToken($r));
$router->dispatch();
// ── AuthApiController ─────────────────────────────────────────
class AuthApiController {
public function __construct(
private readonly AuthService $authService,
private readonly BearerTokenAuthMiddleware $tokens,
private readonly ApiAuthMiddleware $auth,
private readonly RateLimitMiddleware $loginLimiter, // 5/min for login
) {}
public function login(ApiRequest $req): ApiResponse {
$this->loginLimiter->handle($req); // stricter for login
$v = new ApiValidator();
$v->required("email", $req->body("email"))
->email("email", $req->body("email", ""))
->required("password", $req->body("password"));
$v->throw();
$user = $this->authService->login($req->body("email"), $req->body("password"));
if ($user === null) {
return ApiResponse::error(["message" => "Invalid email or password."], 401);
}
$token = $this->tokens->createToken($user["id"], "web_login");
return ApiResponse::success([
"token" => $token,
"user" => ["id" => $user["id"], "name" => $user["name"], "role" => $user["role"]],
]);
}
public function me(ApiRequest $req): ApiResponse {
$user = $this->auth->requireAuth($req);
return ApiResponse::success(["id" => $user["user_id"], "name" => $user["name"], "role" => $user["role"]]);
}
public function logout(ApiRequest $req): ApiResponse {
$token = $req->bearerToken();
if ($token) $this->tokens->revokeToken($token);
return ApiResponse::noContent();
}
}Quick Quiz
Module Quiz
Which HTTP status code should a REST API return when a resource is not found?
Tip
Tip
Practice Mini Project Blog System Part 9 Complete REST API 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 Mini Project: Blog System - Part 9 (Complete REST API)
Practice Task
Note
Practice Task - (1) Write a working example of Mini Project Blog System Part 9 Complete REST API 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 Mini Project Blog System Part 9 Complete REST API 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?