In today's digital age, applications need to communicate with each other seamlessly. REST (Representational State Transfer) APIs are a popular way for different software systems to exchange data over the internet. This tutorial will introduce you to the basics of creating and consuming REST APIs using PHP.
REST is an architectural style that uses standard HTTP methods like GET, POST, PUT, DELETE, etc., to perform operations on resources. It follows a client-server architecture where clients request resources from servers and receive responses in various formats such as JSON or XML.
Before we dive into creating a REST API in PHP, ensure you have the following:
We'll create a simple REST API for managing users. This will include endpoints to get all users, get a single user by ID, create a new user, update an existing user, and delete a user.
Create the following directory structure:
rest-api/
āāā index.php
āāā api/
ā āāā User.php
āāā models/
ā āāā User.php
āāā config/
ā āāā database.php
In config/database.php, set up your database connection:
<?php
return [
'host' => 'localhost',
'dbname' => 'your_database_name',
'username' => 'your_username',
'password' => 'your_password'
];
In models/User.php, define a simple model to interact with the database:
<?php
class User {
private $db;
public function __construct($db) {
$this->db = $db;
}
public function getAllUsers() {
$query = "SELECT * FROM users";
$stmt = $this->db->prepare($query);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function getUserById($id) {
$query = "SELECT * FROM users WHERE id = :id";
$stmt = $this->db->prepare($query);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
}
public function createUser($data) {
$query = "INSERT INTO users (name, email) VALUES (:name, :email)";
$stmt = $this->db->prepare($query);
$stmt->bindParam(':name', $data['name']);
$stmt->bindParam(':email', $data['email']);
return $stmt->execute();
}
public function updateUser($id, $data) {
$query = "UPDATE users SET name = :name, email = :email WHERE id = :id";
$stmt = $this->db->prepare($query);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->bindParam(':name', $data['name']);
$stmt->bindParam(':email', $data['email']);
return $stmt->execute();
}
public function deleteUser($id) {
$query = "DELETE FROM users WHERE id = :id";
$stmt = $this->db->prepare($query);
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
return $stmt->execute();
}
}
In api/User.php, create a controller to handle API requests:
<?php
require_once '../config/database.php';
require_once '../models/User.php';
class UserController {
private $userModel;
public function __construct() {
$dbConfig = require('../config/database.php');
$dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['dbname']}";
$pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password']);
$this->userModel = new User($pdo);
}
public function getAllUsers() {
$users = $this->userModel->getAllUsers();
return json_encode(['status' => 'success', 'data' => $users]);
}
public function getUserById($id) {
$user = $this->userModel->getUserById($id);
if ($user) {
return json_encode(['status' => 'success', 'data' => $user]);
} else {
return json_encode(['status' => 'error', 'message' => 'User not found']);
}
}
public function createUser() {
$data = json_decode(file_get_contents("php://input"), true);
if ($this->userModel->createUser($data)) {
return json_encode(['status' => 'success', 'message' => 'User created successfully']);
} else {
return json_encode(['status' => 'error', 'message' => 'Failed to create user']);
}
}
public function updateUser($id) {
$data = json_decode(file_get_contents("php://input"), true);
if ($this->userModel->updateUser($id, $data)) {
return json_encode(['status' => 'success', 'message' => 'User updated successfully']);
} else {
return json_encode(['status' => 'error', 'message' => 'Failed to update user']);
}
}
public function deleteUser($id) {
if ($this->userModel->deleteUser($id)) {
return json_encode(['status' => 'success', 'message' => 'User deleted successfully']);
} else {
return json_encode(['status' => 'error', 'message' => 'Failed to delete user']);
}
}
}
index.phpIn index.php, route the requests to the appropriate controller methods:
<?php
header('Content-Type: application/json');
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = explode('/', $uri);
require_once 'api/User.php';
$userController = new UserController();
switch ($uri[1]) {
case 'users':
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
if (isset($uri[2])) {
echo $userController->getUserById($uri[2]);
} else {
echo $userController->getAllUsers();
}
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo $userController->createUser();
}
break;
case 'update':
if ($_SERVER['REQUEST_METHOD'] === 'PUT' && isset($uri[2])) {
echo $userController->updateUser($uri[2]);
}
break;
case 'delete':
if ($_SERVER['REQUEST_METHOD'] === 'DELETE' && isset($uri[2])) {
echo $userController->deleteUser($uri[2]);
}
break;
default:
http_response_code(404);
echo json_encode(['status' => 'error', 'message' => 'Endpoint not found']);
}
You can test your API using tools like Postman or curl. Here are some examples:
curl -X GET http://localhost/rest-api/index.php/users
curl -X GET http://localhost/rest-api/index.php/users/1
curl -X POST http://localhost/rest-api/index.php/users \
-H "Content-Type: application/json" \
-d '{"name": "John Doe", "email": "john@example.com"}'
curl -X PUT http://localhost/rest-api/index.php/update/1 \
-H "Content-Type: application/json" \
-d '{"name": "Jane Doe", "email": "jane@example.com"}'
curl -X DELETE http://localhost/rest-api/index.php/delete/1
This tutorial has covered the basics of creating a REST API in PHP. You've learned how to set up your environment, create models and controllers, handle HTTP requests, and test your API. By following these steps and best practices, you can build robust and secure APIs for your applications.