APIs allow PHP applications to communicate with frontend apps, mobile apps, or other systems. In this guide, youβll build a fully functional REST API in PHP with:
β
CRUD operations (Create, Read, Update, Delete)
β
JSON responses
β
Database integration (MySQL)
β
Best practices for API development
By the end, youβll have a complete working API! Letβs dive in. π
1οΈβ£ What is a REST API?
π‘ A REST API (Representational State Transfer) is a web service that allows clients to send HTTP requests and get JSON responses.
Common HTTP methods used in REST APIs:
Method | Action |
---|---|
GET | Retrieve data |
POST | Create new data |
PUT/PATCH | Update existing data |
DELETE | Remove data |
2οΈβ£ Setting Up the Project Structure
π Create a new folder php-rest-api
and inside, set up the following structure:
php-rest-api/
βββ api/
β βββ index.php (Main API entry point)
β βββ users.php (User API logic)
βββ config/
β βββ Database.php (Database connection)
βββ .htaccess (Rewrite rules for clean URLs)
βββ composer.json (For autoloading)
3οΈβ£ Creating the MySQL Database
Run the following SQL command to create the users
table:
CREATE DATABASE api_db;
USE api_db;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
π₯ What happens?
β
The users
table stores user details.
β
id
is the primary key (auto-increment).
β
created_at
stores the timestamp of creation.
4οΈβ£ Database Connection (config/Database.php
)
Create a PHP class to connect to MySQL using PDO.
<?php
class Database {
private $host = "localhost";
private $db_name = "api_db";
private $username = "root";
private $password = "";
public $conn;
public function connect() {
$this->conn = null;
try {
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
return $this->conn;
}
}
?>
π₯ Why use PDO?
β
Prevents SQL injection.
β
Supports multiple databases.
5οΈβ£ Creating the User API (api/users.php
)
Now, weβll create an API to handle CRUD operations.
<?php
header("Content-Type: application/json");
require_once "../config/Database.php";
$database = new Database();
$conn = $database->connect();
// Handle API requests
$request_method = $_SERVER["REQUEST_METHOD"];
switch ($request_method) {
case "GET":
getUsers($conn);
break;
case "POST":
createUser($conn);
break;
case "PUT":
updateUser($conn);
break;
case "DELETE":
deleteUser($conn);
break;
default:
echo json_encode(["message" => "Invalid Request"]);
break;
}
// Function to retrieve users
function getUsers($conn) {
$stmt = $conn->prepare("SELECT * FROM users ORDER BY created_at DESC");
$stmt->execute();
echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
}
// Function to create a new user
function createUser($conn) {
$data = json_decode(file_get_contents("php://input"), true);
if (!isset($data["name"]) || !isset($data["email"])) {
echo json_encode(["error" => "Invalid input"]);
return;
}
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
if ($stmt->execute([$data["name"], $data["email"]])) {
echo json_encode(["message" => "User created successfully"]);
} else {
echo json_encode(["error" => "Failed to create user"]);
}
}
// Function to update a user
function updateUser($conn) {
parse_str(file_get_contents("php://input"), $_PUT);
if (!isset($_PUT["id"]) || !isset($_PUT["name"]) || !isset($_PUT["email"])) {
echo json_encode(["error" => "Invalid input"]);
return;
}
$stmt = $conn->prepare("UPDATE users SET name = ?, email = ? WHERE id = ?");
if ($stmt->execute([$_PUT["name"], $_PUT["email"], $_PUT["id"]])) {
echo json_encode(["message" => "User updated successfully"]);
} else {
echo json_encode(["error" => "Failed to update user"]);
}
}
// Function to delete a user
function deleteUser($conn) {
parse_str(file_get_contents("php://input"), $_DELETE);
if (!isset($_DELETE["id"])) {
echo json_encode(["error" => "Invalid input"]);
return;
}
$stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
if ($stmt->execute([$_DELETE["id"]])) {
echo json_encode(["message" => "User deleted successfully"]);
} else {
echo json_encode(["error" => "Failed to delete user"]);
}
}
?>
π₯ Whatβs happening?
β
GET /api/users.php
β Fetches all users.
β
POST /api/users.php
β Creates a new user.
β
PUT /api/users.php
β Updates user data.
β
DELETE /api/users.php
β Deletes a user.
6οΈβ£ Creating the API Entry Point (api/index.php
)
To make API requests cleaner, create an index file.
<?php
header("Content-Type: application/json");
echo json_encode(["message" => "Welcome to PHP REST API"]);
?>
π₯ Now you can test the API!
7οΈβ£ Enabling Clean URLs with .htaccess
π‘ To remove ?id=1
from URLs, add this file in api/.htaccess
:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^users/([0-9]+)$ users.php?id=$1 [L]
π₯ Now you can access:
http://localhost/php-rest-api/api/users
instead of:
http://localhost/php-rest-api/api/users.php
8οΈβ£ Complete Working Code
Hereβs the entire project:
β
Database Connection (config/Database.php
)
<?php
class Database {
private $host = "localhost";
private $db_name = "api_db";
private $username = "root";
private $password = "";
public $conn;
public function connect() {
$this->conn = null;
try {
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
return $this->conn;
}
}
?>
β
User API (api/users.php
) β See step 5.
β
API Entry Point (api/index.php
) β See step 6.
π₯ You now have a fully functional PHP REST API! π
π Final Thoughts
Now you know how to:
β
Create a REST API using PHP & MySQL
β
Handle GET, POST, PUT, DELETE requests
β
Return JSON responses
β
Use .htaccess
for clean URLs
π Next: Deploy a PHP Application
Happy coding! ππ