Framework như Laravel giúp xây dựng API nhanh hơn, nhưng hiểu cách xây dựng API bằng PHP thuần sẽ giúp bạn hiểu sâu hơn về cách web hoạt động.
RESTful API là gì?
- URL đại diện cho tài nguyên:
/api/posts,/api/posts/1 - HTTP method xác định hành động: GET (đọc), POST (tạo), PUT (cập nhật), DELETE (xóa)
- Response là JSON, có status code phù hợp
- Stateless: mỗi request độc lập, không lưu trạng thái trên server
Entry Point và Routing
<?php
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
$uri = rtrim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
match(true) {
$method === 'GET' && $uri === '/api/posts'
=> (new PostController())->index(),
$method === 'POST' && $uri === '/api/posts'
=> (new PostController())->store(),
default => http_response_code(404) && echo json_encode(['error' => 'Not Found']),
};
Controller
class PostController {
private PDO $db;
public function __construct() {
$this->db = new PDO('mysql:host=localhost;dbname=blog', 'root', '');
}
public function index(): void {
$posts = $this->db->query("SELECT * FROM posts ORDER BY id DESC")
->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(['data' => $posts]);
}
public function store(): void {
$input = json_decode(file_get_contents('php://input'), true);
if (empty($input['title'])) {
http_response_code(422);
echo json_encode(['error' => 'Title là bắt buộc']);
return;
}
$stmt = $this->db->prepare("INSERT INTO posts (title) VALUES (:title)");
$stmt->execute(['title' => $input['title']]);
http_response_code(201);
echo json_encode(['id' => $this->db->lastInsertId()]);
}
}
Xác thực bằng API Token
function authenticate(): void {
$token = str_replace('Bearer ', '', $_SERVER['HTTP_AUTHORIZATION'] ?? '');
if ($token !== getenv('API_SECRET')) {
http_response_code(401);
echo json_encode(['error' => 'Unauthorized']);
exit;
}
}
Xây dựng API bằng PHP thuần dạy bạn những gì framework ẩn đi. Sau khi làm xong, bạn sẽ thực sự hiểu tại sao Laravel lại tiết kiệm nhiều thời gian đến vậy.
Kết luận
Một RESTful API với PHP thuần chỉ cần: entry point xử lý routing, controller xử lý logic, PDO kết nối database, và json_encode để trả về dữ liệu.
Chưa có bình luận. Hãy là người đầu tiên!