Creating a Simple RESTful API in PHP for Blog Management

Creating a Simple RESTful API in PHP for Blog Management

 

In this blog post, we'll create a simple RESTful API in PHP that allows for CRUD operations on a 'blogs' resource. Each task will have an id, title, description, and status. Let's dive in!

Prerequisites

Before we start, ensure you have the following: 

  • A server running PHP (e.g., XAMPP, WAMP, or a web server with PHP support)
  • A database (we'll use MySQL in this example)
  • Basic understanding of PHP and MySQL

Step 1: Create Database

First, we need a database to store our blogs. Create a database named youtube (in my case) and a table blogs with the following structure:

 CREATE DATABASE blogs;  
 USE blogs;  
 CREATE TABLE blogs (  
   id INT AUTO_INCREMENT PRIMARY KEY,  
   title VARCHAR(255) NOT NULL,  
   description TEXT,  
   status VARCHAR(50) NOT NULL  
 );  

Step 2: Creating the API

 Create a new directory for your project, for example, practice_api and inside it, create a file named api.php. This file will handle all API requests.

api.php

 <?php   
 header("Content-Type: application/json");  
 // Database connection  
 $servername = "localhost";  
 $username = "root";   
 $password = "";  
 $dbname = "youtube";  
 $conn = new mysqli($servername, $username, $password, $dbname);  
 if($conn->connect_error) {  
   die(json_encode(["error" => "Connection failed: " . $conn->connect_error]));  
 }  
 $method = $_SERVER['REQUEST_METHOD'];  
 $req_data = json_decode(file_get_contents('php://input'), true);  
 $id = $_GET['id'] ?? null;  
 switch ($method) {  
   case 'POST':  
     $title = $req_data['title'];  
     $description = $req_data['description'];  
     $status = $req_data['status'];  
     $sql = "INSERT INTO `blogs`(`title`, `description`, `status`) VALUES  
     ('$title', '$description', '$status')";  
     if($conn->query($sql) === TRUE) {  
       echo json_encode(["success" => true, "message" => "New record created successfully"]);  
     }else{  
       echo json_encode(["success" => false, "message" => $conn->error]);  
     }  
     break;  
   case 'GET':  
     if($id){  
       $sql = "SELECT * FROM blogs WHERE id = '$id'";  
       $result = $conn->query($sql);  
       $data = $result->fetch_assoc();  
     }else{  
       $sql = "SELECT * FROM blogs";  
       $result = $conn->query($sql);  
       $data = $result->fetch_all(MYSQLI_ASSOC);  
     }  
     echo json_encode($data);  
     break;  
   case 'PUT':  
     $title = $req_data['title'];  
     $description = $req_data['description'];  
     $status = $req_data['status'];  
     $sql = "UPDATE blogs SET title = '$title', description = '$description', status = '$status' WHERE id = '$id'";  
     if($conn->query($sql) === TRUE){  
       echo json_encode(["success" => true, "message" => "Record updated successfully"]);  
     }else{  
       echo json_encode(["success" => false, "message" => $conn->error]);  
     }  
     break;  
   case "DELETE":  
     $sql = "DELETE FROM blogs WHERE id = '$id'";  
     if($conn->query($sql) === TRUE){  
       echo json_encode(["success" => true, "message" => "Record deleted successfully"]);  
     }else{  
       echo json_encode(["success" => false, "message" => $conn->error]);  
     }  
     break;  
     default:  
     echo json_encode(['success' => false, "message" => "Method not allowed"]);  
 }  
 $conn->close();  
 ?>  

Step 3: Testing the API

You can use tools like Postman or curl to test the API. Here are some examples:

Create a new blog (POST) 

 curl --location 'http://localhost/youtube/practice_api/api.php' \  
 --header 'Content-Type: application/json' \  
 --data '{  
   "title": "Blog Title1",  
   "description": "Blog description1",  
   "status": 1  
 }'  
Get all blogs (GET)
 curl --location 'http://localhost/youtube/practice_api/api.php'  
Get a single blog by ID (GET)
 curl --location 'http://localhost/youtube/practice_api/api.php?id=4'  
Update a blog (PUT)
 curl --location --request PUT 'http://localhost/youtube/practice_api/api.php?id=4' \  
 --header 'Content-Type: application/json' \  
 --data '{  
   "title": "Blog Title1 updated",  
   "description": "Blog description1 updated",  
   "status": 0  
 }'  
Delete a task (DELETE)
 curl --location --request DELETE 'http://localhost/youtube/practice_api/api.php?id=3'  

Conclusion

In this tutorial, we create a simple RESTful API in PHP for managing blogs with basic CRUD operations. This setup can be expanded with more features such as user authentication, input validation, and error handling to make it production-ready. Happy coding!

Post a Comment

0 Comments