Building a Simple REST API in PHP: The Quick Guide πŸš€

Building a Simple REST API in PHP: The Quick Guide πŸš€

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! πŸŽ‰πŸš€

Leave a Reply