Examples of Creating a REST API with PHP

Learn three practical examples of creating a REST API using PHP, perfect for beginners and tech enthusiasts.
By Taylor

Introduction to Creating a REST API with PHP

Creating a REST API with PHP allows you to build flexible applications that can interact with other services or front-end applications. REST (Representational State Transfer) is an architectural style that uses standard HTTP methods like GET, POST, PUT, and DELETE. In this article, we’ll explore three diverse examples, each showcasing different aspects of REST API development in PHP.

Example 1: Simple CRUD Operations

Context

This example demonstrates a basic REST API that performs Create, Read, Update, and Delete (CRUD) operations on a list of users. This is a foundational example that helps you understand the core principles of RESTful APIs.

<?php
// Define the data source
$users = [];

// Function to return all users
function getUsers() {
    global $users;
    header('Content-Type: application/json');
    echo json_encode($users);
}

// Function to add a new user
function addUser($user) {
    global $users;
    $users[] = $user;
    header('HTTP/1.1 201 Created');
}

// Function to update a user
function updateUser($id, $user) {
    global $users;
    if (isset($users[$id])) {
        $users[$id] = $user;
        header('HTTP/1.1 200 OK');
    } else {
        header('HTTP/1.1 404 Not Found');
    }
}

// Function to delete a user
function deleteUser($id) {
    global $users;
    if (isset($users[$id])) {
        unset($users[$id]);
        header('HTTP/1.1 204 No Content');
    } else {
        header('HTTP/1.1 404 Not Found');
    }
}

// Main logic to handle requests
$requestMethod = $_SERVER['REQUEST_METHOD'];
if ($requestMethod == 'GET') {
    getUsers();
} elseif ($requestMethod == 'POST') {
    $user = json_decode(file_get_contents('php://input'), true);
    addUser($user);
} elseif ($requestMethod == 'PUT') {
    $id = (int)$_GET['id'];
    $user = json_decode(file_get_contents('php://input'), true);
    updateUser($id, $user);
} elseif ($requestMethod == 'DELETE') {
    $id = (int)$_GET['id'];
    deleteUser($id);
} else {
    header('HTTP/1.1 405 Method Not Allowed');
}
?>

Notes

  • This example uses an array to store user data, which is not persistent. In a real-world application, you’d typically use a database.
  • Ensure to handle errors and invalid input in a production environment.

Example 2: API with Database Integration

Context

In this example, we will create a REST API that interacts with a MySQL database to manage products. This is a practical scenario for eCommerce applications.

<?php
// Database connection settings
$host = 'localhost';
$db = 'your_database';
$user = 'your_username';
$password = 'your_password';

// Create a MySQL database connection
$conn = new mysqli($host, $user, $password, $db);
if ($conn->connect_error) {
    die('Database connection failed: ' . $conn->connect_error);
}

// Function to get all products
function getProducts($conn) {
    $result = $conn->query('SELECT * FROM products');
    $products = $result->fetch_all(MYSQLI_ASSOC);
    header('Content-Type: application/json');
    echo json_encode($products);
}

// Function to add a new product
function addProduct($conn, $product) {
    $stmt = $conn->prepare('INSERT INTO products (name, price) VALUES (?, ?)');
    $stmt->bind_param('sd', $product['name'], $product['price']);
    $stmt->execute();
    header('HTTP/1.1 201 Created');
}

// Function to update a product
function updateProduct($conn, $id, $product) {
    $stmt = $conn->prepare('UPDATE products SET name = ?, price = ? WHERE id = ?');
    $stmt->bind_param('sdi', $product['name'], $product['price'], $id);
    if ($stmt->execute()) {
        header('HTTP/1.1 200 OK');
    } else {
        header('HTTP/1.1 404 Not Found');
    }
}

// Function to delete a product
function deleteProduct($conn, $id) {
    $stmt = $conn->prepare('DELETE FROM products WHERE id = ?');
    $stmt->bind_param('i', $id);
    if ($stmt->execute()) {
        header('HTTP/1.1 204 No Content');
    } else {
        header('HTTP/1.1 404 Not Found');
    }
}

// Main logic to handle requests
$requestMethod = $_SERVER['REQUEST_METHOD'];
if ($requestMethod == 'GET') {
    getProducts($conn);
} elseif ($requestMethod == 'POST') {
    $product = json_decode(file_get_contents('php://input'), true);
    addProduct($conn, $product);
} elseif ($requestMethod == 'PUT') {
    $id = (int)$_GET['id'];
    $product = json_decode(file_get_contents('php://input'), true);
    updateProduct($conn, $id, $product);
} elseif ($requestMethod == 'DELETE') {
    $id = (int)$_GET['id'];
    deleteProduct($conn, $id);
} else {
    header('HTTP/1.1 405 Method Not Allowed');
}
$conn->close();
?>

Notes

  • Replace your_database, your_username, and your_password with actual database credentials.
  • This example uses prepared statements to prevent SQL injection attacks.

Example 3: Secured API with Authentication

Context

In this final example, we’ll implement a REST API that includes a simple token-based authentication mechanism to secure access to user data. This is essential for protecting sensitive information.

<?php
// Dummy user credentials for demonstration
$users = [
    'user1' => 'password1',
    'user2' => 'password2'
];

// Simple token generation function
function generateToken($username) {
    return base64_encode($username . ':' . time());
}

// Function to authenticate a user
function authenticate($username, $password) {
    global $users;
    if (isset($users[$username]) && $users[$username] === $password) {
        return generateToken($username);
    }
    return null;
}

// Function to get user data
function getUserData($token) {
    // In a real application, validate the token and return user data
    header('Content-Type: application/json');
    echo json_encode(['message' => 'User data accessed successfully']);
}

// Main logic to handle requests
$requestMethod = $_SERVER['REQUEST_METHOD'];
if ($requestMethod == 'POST' && isset($_GET['action']) && $_GET['action'] === 'login') {
    $data = json_decode(file_get_contents('php://input'), true);
    $token = authenticate($data['username'], $data['password']);
    if ($token) {
        header('Content-Type: application/json');
        echo json_encode(['token' => $token]);
    } else {
        header('HTTP/1.1 401 Unauthorized');
    }
} elseif ($requestMethod == 'GET' && isset($_GET['token'])) {
    getUserData($_GET['token']);
} else {
    header('HTTP/1.1 405 Method Not Allowed');
}
?>

Notes

  • This is a basic example of authentication; consider using libraries like JWT (JSON Web Tokens) for a more robust solution.
  • Always use HTTPS in production environments to secure data in transit.

By following these examples, you should have a solid foundation for creating a REST API with PHP. Feel free to expand on these examples by adding features such as error handling, input validation, and more advanced authentication methods!