PHP - Build Rest API Without any Framework

PHP - Build Rest API Without any Framework

Written : 2022-01-13 Last Update : 2022-01-13

Setup

Let's take a quick look at creating basic REST API using PHP ! Assuming that you already have a working understanding of PHP, SQL and Server Request Methods like GET, POST etc, We will move forward quickly.

I have a simple table named tasks , with three columns for id, task and status.

$sql = "CREATE TABLE `tasks` (
    `id` tinyint(4) NOT NULL,
    `task` tinytext NOT NULL,
    `status` tinyint(4) NOT NULL DEFAULT 0
)";

In a file named db.php, I have connected to a Database named as apis, where I have my Table tasks.

<?php
$servername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "apis";
        
$conn = mysqli_connect($servername, $dbUsername, $dbPassword, $dbName);
if(!$conn){
    die("Connection Failed : ".mysqli_connect_error());
}
?>

I will create a single file named index.php and in that file we will do CRUD Operation Based on The Request Type.
For A GET Request , we will send the list of tasks available, for a PUT Request we will accept a value for task and will add that to our database, for a POST Request, we will mondify the status of our task from 0 (pending) to 1(completed), and finally for DELETE Request, we will delete a task based on the ID provided.

Now here We have simply set our headers, for Content-Type and Allowed Origins.

 <?php
 header("Access-Control-Allow-Origin: *");
 header("Content-Type: application/json; charset=UTF-8");
 
 $method = $_SERVER['REQUEST_METHOD'];
 // we get the type of request made and store it in $method 
 require 'db.php';
 // for the sake of tutorial we will simply put the db connection
 // file in global scope 
 ?>

Code

We will find the type of request being made to server and will handle out code base according to that.

  switch ($method) {
     case 'GET':
         $sql = "SELECT * FROM tasks";
         $result = mysqli_query($conn, $sql);
         $tasks = array();
         if (mysqli_num_rows($result) > 0) {
             while ($row = mysqli_fetch_assoc($result)) {
                 array_push($tasks, $row);
             }
             $response = array(
                 'status' => true,
                 'msg' => "Fetched Successfully",
                 'data' => $tasks
             );
             echo json_encode($response);
         } else {
             $response = array(
                 'status' => true,
                 'msg' => "No Tasks Found",
                 'data' => $tasks
             );
             echo json_encode($response);
         }
         break;
     case 'PUT':
         // get the data send as JSON and decode it
         $data = json_decode(file_get_contents("php: input"));
         //
         if (is_null($data)) {
             $response = array(
                 'status' => false,
                 'msg' => "Empty Fields"
             );
             echo json_encode($response);
         } else {
             $sql = "INSERT INTO tasks (task) VALUES (?)";
             if ($stmt = mysqli_prepare($conn, $sql)) {
                 // Bind variables to the prepare statement as parameters
                 mysqli_stmt_bind_param($stmt, "s" $data->task);
                 mysqli_stmt_execute($stmt);
                 $response = array(
                     'status' => true,
                     'msg' => "Added Successfully"
                 );
                 echo json_encode($response);
             } else {
                 $response = array(
                     'status' => false,
                     'msg' => "Error Preparing Statements"
                 );
                 echo json_encode($response);
             }
         }
         break;
     case 'POST':
         // POST REQ
         // Modify Status
         // get the data send as JSON and decode it
         $data = json_decode(file_get_contents("php: input"));
         if (is_null($data)) {
             $response = array(
                 'status' => false,
                 'msg' => "Empty Fields"
             );
             echo json_encode($response);
         } else {
             $sql = "UPDATE tasks SET status = ? WHERE i = ?";
             if ($stmt = mysqli_prepare($conn, $sql)) {
                 // Bind variables to the prepare statement as parameters
                 mysqli_stmt_bind_param($stmt, "ss" $data->status, $data->id);
                 mysqli_stmt_execute($stmt);
                 // not getting deeper into checking the response
                 $response = array(
                     'status' => true,
                     'msg' => "Updated Successfully"
                 );
                 echo json_encode($response);
             } else {
                 $response = array(
                     'status' => false,
                     'msg' => "Error Preparing Statements"
                 );
                 echo json_encode($response);
             }
         }
         break;
     case 'DELETE':
         // Delete A Task
         // get the data send as JSON and decode it
         $data = json_decode(file_get_contents("php: input"));
         if (is_null($data)) {
             $response = array(
                 'status' => false,
                 'msg' => "Empty Fields"
             );
             echo json_encode($response);
         } else {
             $sql = "DELETE FROM tasks WHERE id = "  $data->id;
             $result = mysqli_query($conn, $sql);
             // assuming that only the valid Ids will be send from UI
             $response = array(
                 'status' => true,
                 'msg' => "Deleted Successfully"
             );
             echo json_encode($response);
         }
         break;
 
     default:
         $response = array(
             'status' => false,
             'msg' => "Unsupported Request Type"
         );
         echo json_encode($response);
 
         break;
 }

Having done this you can use a REST client like Postman (opens in a new tab) to make requests.

Given below is a sample response you will get if try to make a request, but with a method other than the ones mentioned above !

{
    "status": false,
    "msg": "Unsupported Request Type"
}