REST API (Representational State Transfer Application Programming Interface) là một cách phổ biến để xây dựng các dịch vụ web. REST API cho phép các ứng dụng giao tiếp với nhau thông qua các phương thức HTTP như GET, POST, PUT và DELETE.
Khái niệm cơ bản về REST API
Các phương thức HTTP phổ biến
- GET: Lấy dữ liệu từ máy chủ.
- POST: Gửi dữ liệu mới đến máy chủ.
- PUT: Cập nhật dữ liệu hiện có trên máy chủ.
- PATCH: Cập nhật một phần của dữ liệu hiện có trên máy chủ.
- DELETE: Xóa dữ liệu từ máy chủ.
Cấu trúc URL RESTful
URL RESTful thường tuân theo một cấu trúc nhất định để đại diện cho các tài nguyên. Ví dụ:
GET /users - Lấy danh sách người dùng
GET /users/{id} - Lấy thông tin người dùng cụ thể
POST /users - Tạo người dùng mới
PUT /users/{id} - Cập nhật thông tin người dùng
DELETE /users/{id} - Xóa người dùng
Chuẩn bị Cơ sở dữ liệu
Trước khi bắt đầu xây dựng REST API, bạn cần chuẩn bị cơ sở dữ liệu để lưu trữ dữ liệu. Dưới đây là một ví dụ về bảng người dùng trong cơ sở dữ liệu MySQL:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Tạo REST API đơn giản với PHP
Bước 1: Tạo cấu trúc thư mục
Tạo cấu trúc thư mục cho dự án REST API của bạn:
/api
/config
Database.php
/controllers
UserController.php
/models
User.php
/routes
index.php
/public
index.php
Bước 2: Tạo tệp cấu hình cơ sở dữ liệu
File: /api/config/Database.php
// filepath: rest-api/api/config/Database.php
class Database {
private $host = "localhost";
private $db_name = "your_database";
private $username = "your_username";
private $password = "your_password";
public $conn;
public function getConnection() {
$this->conn = null;
try {
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->exec("set names utf8");
} catch (PDOException $exception) {
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
Bước 3: Tạo Model
File: /api/models/User.php
// filepath: rest-api/api/models/User.php
class User {
private $conn;
private $table_name = "users";
public $id;
public $name;
public $email;
public $created_at;
public function __construct($db) {
$this->conn = $db;
}
public function read() {
$query = "SELECT id, name, email, created_at FROM " . $this->table_name . " ORDER BY created_at DESC";
$stmt = $this->conn->prepare($query);
$stmt->execute();
return $stmt;
}
public function create() {
$query = "INSERT INTO " . $this->table_name . " SET name=:name, email=:email, created_at=:created_at";
$stmt = $this->conn->prepare($query);
$this->name = htmlspecialchars(strip_tags($this->name));
$this->email = htmlspecialchars(strip_tags($this->email));
$this->created_at = htmlspecialchars(strip_tags($this->created_at));
$stmt->bindParam(":name", $this->name);
$stmt->bindParam(":email", $this->email);
$stmt->bindParam(":created_at", $this->created_at);
if ($stmt->execute()) {
return true;
}
return false;
}
public function update() {
$query = "UPDATE " . $this->table_name . " SET name = :name, email = :email WHERE id = :id";
$stmt = $this->conn->prepare($query);
$this->name = htmlspecialchars(strip_tags($this->name));
$this->email = htmlspecialchars(strip_tags($this->email));
$this->id = htmlspecialchars(strip_tags($this->id));
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':email', $this->email);
$stmt->bindParam(':id', $this->id);
if ($stmt->execute()) {
return true;
}
return false;
}
public function delete() {
$query = "DELETE FROM " . $this->table_name . " WHERE id = ?";
$stmt = $this->conn->prepare($query);
$this->id = htmlspecialchars(strip_tags($this->id));
$stmt->bindParam(1, $this->id);
if ($stmt->execute()) {
return true;
}
return false;
}
}
Bước 4: Tạo Controller
File: /api/controllers/UserController.php
// filepath: rest-api/api/controllers/UserController.php
require_once '../models/User.php';
class UserController {
private $db;
private $requestMethod;
private $userId;
private $user;
public function __construct($db, $requestMethod, $userId) {
$this->db = $db;
$this->requestMethod = $requestMethod;
$this->userId = $userId;
$this->user = new User($db);
}
public function processRequest() {
switch ($this->requestMethod) {
case 'GET':
if ($this->userId) {
$response = $this->getUser($this->userId);
} else {
$response = $this->getAllUsers();
};
break;
case 'POST':
$response = $this->createUser();
break;
case 'PUT':
$response = $this->updateUser($this->userId);
break;
case 'DELETE':
$response = $this->deleteUser($this->userId);
break;
default:
$response = $this->notFoundResponse();
break;
}
header($response['status_code_header']);
if ($response['body']) {
echo $response['body'];
}
}
private function getAllUsers() {
$result = $this->user->read();
$users = $result->fetchAll(PDO::FETCH_ASSOC);
$response['status_code_header'] = 'HTTP/1.1 200 OK';
$response['body'] = json_encode($users);
return $response;
}
private function getUser($id) {
$this->user->id = $id;
$result = $this->user->read();
$user = $result->fetch(PDO::FETCH_ASSOC);
if (!$user) {
return $this->notFoundResponse();
}
$response['status_code_header'] = 'HTTP/1.1 200 OK';
$response['body'] = json_encode($user);
return $response;
}
private function createUser() {
$input = (array) json_decode(file_get_contents('php://input'), TRUE);
if (!$this->validateUser($input)) {
return $this->unprocessableEntityResponse();
}
$this->user->name = $input['name'];
$this->user->email = $input['email'];
$this->user->created_at = date('Y-m-d H:i:s');
if ($this->user->create()) {
$response['status_code_header'] = 'HTTP/1.1 201 Created';
$response['body'] = json_encode(['message' => 'User Created']);
return $response;
}
return $this->unprocessableEntityResponse();
}
private function updateUser($id) {
$input = (array) json_decode(file_get_contents('php://input'), TRUE);
if (!$this->validateUser($input)) {
return $this->unprocessableEntityResponse();
}
$this->user->id = $id;
$this->user->name = $input['name'];
$this->user->email = $input['email'];
if ($this->user->update()) {
$response['status_code_header'] = 'HTTP/1.1 200 OK';
$response['body'] = json_encode(['message' => 'User Updated']);
return $response;
}
return $this->unprocessableEntityResponse();
}
private function deleteUser($id) {
$this->user->id = $id;
if ($this->user->delete()) {
$response['status_code_header'] = 'HTTP/1.1 200 OK';
$response['body'] = json_encode(['message' => 'User Deleted']);
return $response;
}
return $this->notFoundResponse();
}
private function validateUser($input) {
if (!isset($input['name']) || !isset($input['email'])) {
return false;
}
return true;
}
private function unprocessableEntityResponse() {
$response['status_code_header'] = 'HTTP/1.1 422 Unprocessable Entity';
$response['body'] = json_encode(['message' => 'Invalid input']);
return $response;
}
private function notFoundResponse() {
$response['status_code_header'] = 'HTTP/1.1 404 Not Found';
$response['body'] = json_encode(['message' => 'Not Found']);
return $response;
}
}
Bước 5: Tạo tệp định tuyến(Routing)
File: /api/routes/index.php
// filepath: rest-api/api/routes/index.php
require "../config/Database.php";
require "../controllers/UserController.php";
$database = new Database();
$db = $database->getConnection();
$requestMethod = $_SERVER["REQUEST_METHOD"];
$userId = isset($_GET['id']) ? $_GET['id'] : null;
$controller = new UserController($db, $requestMethod, $userId);
$controller->processRequest();
Bước 6: Tạo điểm vào chính(Bootstrap/Entry point)
File: /public/index.php
// filepath: rest-api/public/index.php
require_once '../api/routes/index.php';
Chạy ứng dụng
Chạy ứng dụng bằng cách sau:
1. Mở terminal và di chuyển đến thư mục public
của ứng dụng.
2. Chạy lệnh php -S localhost:8000
để khởi chạy máy chủ web tích hợp sẵn trong PHP.
3. Sử dụng công cụ như Postman hoặc curl để gửi các yêu cầu HTTP đến API của bạn.
Kết luận
REST API là một cách mạnh mẽ để xây dựng các dịch vụ web, cho phép các ứng dụng giao tiếp với nhau thông qua các phương thức HTTP. Bằng cách hiểu và sử dụng REST API, bạn có thể phát triển các ứng dụng PHP linh hoạt và mạnh mẽ hơn.