Open In App

CRUD Operation in REST API using PHP

Last Updated : 10 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

A REST (Representational State Transfer) API allows communication between a client and a server through HTTP requests. PHP, a widely used server-side scripting language, is well-suited for creating REST APIs due to its simplicity and rich ecosystem. This article provides a step-by-step guide on building a REST API in PHP, covering various approaches, detailed explanations, syntax, examples, and output. Additionally, we'll discuss the prerequisites, provide a structured folder setup, demonstrate the process of creating and testing a basic REST API, and include steps for creating a database with sample data.

These are the following topics that we are going to discuss:

What is a REST API?

A REST API (Representational State Transfer Application Programming Interface) is an architectural style that allows communication between different software applications over the HTTP protocol. REST APIs use standard HTTP methods such as GET, POST, PUT, DELETE, etc., to perform operations on resources, which are typically represented in formats like JSON or XML. REST APIs are stateless, meaning each request from a client must contain all the information needed to understand and process the request, with no session state stored on the server

Steps to Set Up XAMPP

Step 1: Download and Install XAMPP

  • Download XAMPP from Apache Friends.
  • Follow the installation wizard to install XAMPP.
  • Once installed, open the XAMPP Control Panel and start the Apache and MySQL services.
Screenshot-2024-09-09-171044
Type in search box xampp Control Panel and click on open

Step 2: Create a MySQL Database

Access phpMyAdmin

  • In the XAMPP Control Panel, click "Admin" next to MySQL. This will open phpMyAdmin.
Screenshot-2024-09-09-171501
  • In phpMyAdmin, click on the "Databases" tab.
image1
  • Create a new database called myapi_db.
image2
Enter database name myapi_db and click on Create button.

Step 3: Create Table

  • After creating the database, select myapi_db.
  • Create a users table with the following fields: id, name, and email.
image4
table model
  • After save we will insert sample data into our users table:
INSERT INTO users (name, email) VALUES
('John Doe', 'john@example.com'),
('Jane Doe', 'jane@example.com'),
('Alice Smith', 'alice@example.com'),
('Bob Brown', 'bob@example.com'),
('Charlie Black', 'charlie@example.com');
  • Copy above query and paste into your database console and press Ctrl+Enter.
Screenshot-2024-09-09-224728
command
  • After inseting sample data into users table:
Screenshot-2024-09-09-224506
Table

Steps to create the PHP REST API

Step 1: Create Project Folder

  • Navigate to the htdocs folder inside the XAMPP installation directory (e.g., C:\xampp\htdocs).
  • Create a new folder called my-php-api.

Command:

mkdir my-php-api

Step 2: Create a Database Connection File

  • Inside the my-php-api folder, create a new folder called config.
  • Inside the config folder, create a file called database.php.
PHP
//  config/database.php
<?php
$host = 'localhost';
$db_name = 'myapi_db';
$username = 'root';
$password = '';

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

Step 3: Create the API File

  • Inside the my-php-api folder, create a new folder called api and a file called users.php
PHP
// api/users.php
<?php
require_once __DIR__ . '/../config/database.php';

header("Content-Type: application/json");

$method = $_SERVER['REQUEST_METHOD'];

switch($method) {
    case 'GET':
        // Handle GET request (Retrieve Users)
        $stmt = $conn->query("SELECT * FROM users");
        $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($users);
        break;

    case 'POST':
        // Handle POST request (Create User)
        $data = json_decode(file_get_contents("php://input"));
        $sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':name', $data->name);
        $stmt->bindParam(':email', $data->email);
        if($stmt->execute()) {
            echo json_encode(['message' => 'User created successfully']);
        }
        break;

    case 'PUT':
        // Handle PUT request (Update User)
        $data = json_decode(file_get_contents("php://input"));
        $sql = "UPDATE users SET name = :name, email = :email WHERE id = :id";
        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':name', $data->name);
        $stmt->bindParam(':email', $data->email);
        $stmt->bindParam(':id', $data->id);
        if($stmt->execute()) {
            echo json_encode(['message' => 'User updated successfully']);
        }
        break;

    case 'DELETE':
        // Handle DELETE request (Delete User)
        $data = json_decode(file_get_contents("php://input"));
        $sql = "DELETE FROM users WHERE id = :id";
        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':id', $data->id);
        if($stmt->execute()) {
            echo json_encode(['message' => 'User deleted successfully']);
        }
        break;

    default:
        http_response_code(405); // Method Not Allowed
        break;
}
?>

Test the API Using Postman

Now that the API is ready, we can test the CRUD operations using Postman. Before sending request using postman we have to set up desktop agent because we are testing locally so follow the given below steps:

  • Access Postman in your browser.
  • Click Postman Agent then select Desktop Agent.
image5

1. Testing the GET Request (Read Users)

  • Open Postman and create a new request.
  • Select the GET method and enter the URL: http://localhost/my-php-api/api/users.php.
  • Click "Send" to fetch all users.

2. Testing the POST Request (Create User)

  • In Postman, select the POST method and enter the URL: http://localhost/my-php-api/api/users.php.
  • In the "Body" tab, select "raw" and "JSON" format.
  • Enter the following JSON:
{
"name": "New User",
"email": "newuser@example.com"
}
  • Click "Send" to create a new user.

3. Testing the PUT Request (Update User)

  • In Postman, select the PUT method and enter the URL: http://localhost/my-php-api/api/users.php.
  • In the "Body" tab, select "raw" and "JSON" format.
  • Enter the following JSON to update the user:
{
"id": 1,
"name": "Updated User",
"email": "updated@example.com"
}
  • Click "Send" to update the user.

4. Testing the DELETE Request (Delete User)

  • In Postman, select the DELETE method and enter the URL: http://localhost/my-php-api/api/users.php.
  • In the "Body" tab, select "raw" and "JSON" format.
  • Enter the following JSON to delete the user:
{
"id": 1
}
  • Click "Send" to delete the user.

Conclusion

In this article, we demonstrated how to build a simple REST API using PHP and MySQL, covering basic CRUD operations. We used XAMPP to run our local server and MySQL database, and Postman to test the API endpoints. By following the steps outlined in this guide, you can easily extend the API and add more functionalities based on your project requirements.


Article Tags :

Similar Reads

three90RightbarBannerImg