Learn How to Create a Simple PHP REST API
Published: 2024-06-07 21:29:21

**Introduction**
In this tutorial, we'll guide you through the process of creating a simple REST API using PHP. REST APIs are essential for web applications as they allow for communication between different software systems. By the end of this tutorial, you'll have a working API that can handle basic CRUD (Create, Read, Update, Delete) operations.

**Step 1: Setting Up the Project**
Create a new directory for your project and set up the necessary files.

- index.php
- config.php
- api.php

**Step 2: Database Configuration**
Create a MySQL database and a table for this example. We'll use a table called users.

```
CREATE DATABASE rest_api_db;
USE rest_api_db;

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    age INT NOT NULL
);

```

**Step 3: Configuring Database Connection**
In config.php, add the database connection details.

```
<?php
$host = 'localhost';
$db_name = 'rest_api_db';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$db_name", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>

```

**Step 4: Creating the API Endpoints**
In api.php, we'll handle the different API requests.

```
<?php
require 'config.php';

$method = $_SERVER['REQUEST_METHOD'];

$request = explode('/', trim($_SERVER['PATH_INFO'], '/'));

switch ($method) {
    case 'GET':
        if (isset($request[0]) && is_numeric($request[0])) {
            getUser($request[0]);
        } else {
            getUsers();
        }
        break;
    case 'POST':
        createUser();
        break;
    case 'PUT':
        if (isset($request[0]) && is_numeric($request[0])) {
            updateUser($request[0]);
        } else {
            echo json_encode(['error' => 'Invalid User ID']);
        }
        break;
    case 'DELETE':
        if (isset($request[0]) && is_numeric($request[0])) {
            deleteUser($request[0]);
        } else {
            echo json_encode(['error' => 'Invalid User ID']);
        }
        break;
    default:
        echo json_encode(['error' => 'Invalid Request Method']);
}

function getUsers() {
    global $pdo;
    $stmt = $pdo->query("SELECT * FROM users");
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($users);
}

// Function to fetch a single user by ID
function getUser($id) {
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([$id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    echo json_encode($user);
}

function createUser() {
    global $pdo;
    $data = json_decode(file_get_contents('php://input'), true);
    $stmt = $pdo->prepare("INSERT INTO users (name, email, age) VALUES (?, ?, ?)");
    if ($stmt->execute([$data['name'], $data['email'], $data['age']])) {
        echo json_encode(['success' => 'User created successfully']);
    } else {
        echo json_encode(['error' => 'Failed to create user']);
    }
}

function updateUser($id) {
    global $pdo;
    $data = json_decode(file_get_contents('php://input'), true);
    $stmt = $pdo->prepare("UPDATE users SET name = ?, email = ?, age = ? WHERE id = ?");
    if ($stmt->execute([$data['name'], $data['email'], $data['age'], $id])) {
        echo json_encode(['success' => 'User updated successfully']);
    } else {
        echo json_encode(['error' => 'Failed to update user']);
    }
}

function deleteUser($id) {
    global $pdo;
    $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
    if ($stmt->execute([$id])) {
        echo json_encode(['success' => 'User deleted successfully']);
    } else {
        echo json_encode(['error' => 'Failed to delete user']);
    }
}
?>

```

**Step 5: Testing the API**
You can test the API endpoints using tools like Postman or curl.

```
// GET all users
curl -X GET http://localhost/simple-php-rest-api/api.php

// GET a single user by ID
curl -X GET http://localhost/simple-php-rest-api/api.php/1

// POST a new user
curl -X POST -H "Content-Type: application/json" -d '{"name": "John Smith", "email": "john.smith@gmail.com", "age": 30}' http://localhost/simple-php-rest-api/api.php

// PUT update a user by ID
curl -X PUT -H "Content-Type: application/json" -d '{"name": "John Smith", "email": "ohn.smith@gmail.com", "age": 25}' http://localhost/simple-php-rest-api/api.php/1

// DELETE a user by ID
curl -X DELETE http://localhost/simple-php-rest-api/api.php/1

```

**Conclusion**
Creating a simple REST API with PHP is straightforward and powerful. With the knowledge gained from this tutorial, you can expand and customize your API to suit your specific needs, adding more functionality and enhancing its robustness.