Build Simple REST API with PHP and MySQL
REST stands for Representational State Transfer. RESTful Web services are one way of providing interoperability between computer systems on the Internet. Rest API help to communicate between the client app and the server application. REST is an architecture style for designing networked applications. A REST API defines a bunch of functions which developers can perform requests and receive responses via HTTP protocol such as GET and POST.
In this tutorial, you will learn to how create CRUD (create, read, update, delete) operation REST API with PHP and MySQL. This is a very simple example, you can just copy paste, and change according to your requirement.
Before started to implement the REST API with PHP and MySQL, look files structure:
- build-simple-rest-api-with-php-mysql
- class
- DBConnection.php
- Student.php.
- student
- create.php
- read.php
- update.php
- delete.php
- .htaccess
- class
Understanding REST API
REST provides a block of HTTP methods which are used to alter the data. The following are common HTTP methods:
- GET — is used for reading and retrieving data.
- POST — is used for inserting data.
- PUT/PATCH — is used for updating data.
- DELETE — is used for deleting data.
Step 1: Create MySQL Database and Table
For this tutorial, you need a MySQL database with the following table:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
CREATE TABLE `student` ( `id` int(11) NOT NULL, `roll_no` varchar(10) DEFAULT 'NULL', `first_name` varchar(255) NOT NULL, `last_name` varchar(255) NOT NULL, `class` varchar(255) NOT NULL, `age` int(11) NOT NULL, `address` varchar(255) NOT NULL, `status` int(1) NOT NULL DEFAULT 0 ) ENGINE=InnoDB DEFAULT CHARSET=latin1; INSERT INTO `student` (`id`, `roll_no`, `first_name`, `last_name`, `class`, `age`, `address`, `status`) VALUES (1, 'R001', 'Tiger', 'Wood', 'LKG', 3, 'USA', 1); ALTER TABLE `student` ADD PRIMARY KEY (`id`); ALTER TABLE `student` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; |
Step 2: Connect to Database file named
DBConnection.php
The code below shows the database credentials
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php /** * @package PHP Rest API(DBConnection) * * @author TechArise Team * * @email info@techarise.com * */ // Database Connection class DBConnection { private $_dbHostname = "localhost"; private $_dbName = "test_DB"; private $_dbUsername = "root"; private $_dbPassword = ""; private $_con; public function __construct() { try { $this->_con = new PDO("mysql:host=$this->_dbHostname;dbname=$this->_dbName", $this->_dbUsername, $this->_dbPassword); $this->_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } } // return Connection public function returnConnection() { return $this->_con; } } ?> |
Step 3: Create class
Create a class file named
Student.php
inside class/ folder.- The Student class handles the CRUD process
__construct()
— Loads the required DBConnection.createStudent()
— Add Student Record.updateStudent()
— Update Student Record.getAllStudent()
— get Student all Records.getStudent()
— get Student single Record.deleteStudent()
— delete Student Record.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 |
<?php /** * @package Student class * * @author TechArise Team * * @email info@techarise.com * */ include("DBConnection.php"); class Student { protected $db; private $_studentID; private $_firstName; private $_lastName; private $_rollNo; private $_className; private $_age; public function setStudentID($studentID) { $this->_studentID = $studentID; } public function setFirstName($firstName) { $this->_firstName = $firstName; } public function setLastName($firstName) { $this->_lastName = $firstName; } public function setRollNo($rollNo) { $this->_rollNo = $rollNo; } public function setClassName($className) { $this->_className = $className; } public function setAge($age) { $this->_age = $age; } public function setAddress($address) { $this->_address = $address; } public function __construct() { $this->db = new DBConnection(); $this->db = $this->db->returnConnection(); } // create Student public function createStudent() { try { $sql = 'INSERT INTO student (first_name, last_name, roll_no, class, age, address, status) VALUES (:first_name, :last_name, :roll_no, :class, :age, :address, :status)'; $data = [ 'first_name' => $this->_firstName, 'last_name' => $this->_lastName, 'roll_no' => $this->_rollNo, 'class' => $this->_className, 'age' => $this->_age, 'address' => $this->_address, 'status' => 1, ]; $stmt = $this->db->prepare($sql); $stmt->execute($data); $status = $stmt->rowCount(); return $status; } catch (Exception $e) { die("Oh noes! There's an error in the query!"); } } // update Student public function updateStudent() { try { $sql = "UPDATE student SET first_name=:first_name, last_name=:last_name, roll_no=:roll_no, class=:class, age=:age, address=:address, status=:status WHERE id=:student_id"; $data = [ 'first_name' => $this->_firstName, 'last_name' => $this->_lastName, 'roll_no' => $this->_rollNo, 'class' => $this->_className, 'age' => $this->_age, 'address' => $this->_address, 'status' => 1, 'student_id' => $this->_studentID ]; $stmt = $this->db->prepare($sql); $stmt->execute($data); $status = $stmt->rowCount(); return $status; } catch (Exception $e) { die("Oh noes! There's an error in the query!"); } } // getAll Student public function getAllStudent() { try { $sql = "SELECT * FROM student"; $stmt = $this->db->prepare($sql); $stmt->execute(); $result = $stmt->fetchAll(\PDO::FETCH_ASSOC); return $result; } catch (Exception $e) { die("Oh noes! There's an error in the query!"); } } // get Student public function getStudent() { try { $sql = "SELECT * FROM student WHERE id=:student_id"; $stmt = $this->db->prepare($sql); $data = [ 'student_id' => $this->_studentID ]; $stmt->execute($data); $result = $stmt->fetch(\PDO::FETCH_ASSOC); return $result; } catch (Exception $e) { die("Oh noes! There's an error in the query!"); } } // delete Student public function deleteStudent() { try { $sql = "DELETE FROM student WHERE id=:student_id"; $stmt = $this->db->prepare($sql); $data = [ 'student_id' => $this->_studentID ]; $stmt->execute($data); $status = $stmt->rowCount(); return $status; } catch (Exception $e) { die("Oh noes! There's an error in the query!"); } } } ?> |
Step 4: Add Student Record — POST Method
Create PHP file named
student/create.php
to insert student records to MySQL database. We will check for POST HTTP request and call method createStudent()
to insert student data to MySQL database table and return JSON data
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?php $requestMethod = $_SERVER["REQUEST_METHOD"]; include('../class/Student.php'); $student = new Student(); switch($requestMethod) { case 'POST': $first_name = $_POST['first_name']; $last_name = $_POST['last_name']; $roll_no = $_POST['roll_no']; $class = $_POST['class']; $age = $_POST['age']; $address = $_POST['address']; $status = $_POST['status']; $student->setFirstName($first_name); $student->setLastName($last_name); $student->setRollNo($roll_no); $student->setClassName($class); $student->setAge($age); $student->setAddress($address); $studentInfo = $student->createStudent(); if(!empty($studentInfo)) { $js_encode = json_encode(array('status'=>TRUE, 'message'=>'Student created Successfully'), true); } else { $js_encode = json_encode(array('status'=>FALSE, 'message'=>'Student creation failed.'), true); } header('Content-Type: application/json'); echo $js_encode; break; default: header("HTTP/1.0 405 Method Not Allowed"); break; } ?> |
In this method
createStudent()
from class Student.php
, we will insert record into student table.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php // create Student public function createStudent() { try { $sql = 'INSERT INTO student (first_name, last_name, roll_no, class, age, address, status) VALUES (:first_name, :last_name, :roll_no, :class, :age, :address, :status)'; $data = [ 'first_name' => $this->_firstName, 'last_name' => $this->_lastName, 'roll_no' => $this->_rollNo, 'class' => $this->_className, 'age' => $this->_age, 'address' => $this->_address, 'status' => 1, ]; $stmt = $this->db->prepare($sql); $stmt->execute($data); $status = $stmt->rowCount(); return $status; } catch (Exception $e) { die("Oh noes! There's an error in the query!"); } } ?> |
Step 5: Read Student Record from the Database — GET Method
Create PHP file named
student/read.php
to get student records to MySQL database. We will check for GET HTTP request and call method getAllStudent()
or getStudent()
to get student data to MySQL database table and return JSON response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php $requestMethod = $_SERVER["REQUEST_METHOD"]; include('../class/Student.php'); $student = new Student(); switch($requestMethod) { case 'GET': $studentID = ''; if($_GET['id']) { $studentID = $_GET['id']; $student->setStudentID($studentID); $studentInfo = $student->getStudent(); } else { $studentInfo = $student->getAllStudent(); } if(!empty($studentInfo)) { $js_encode = json_encode(array('status'=>TRUE, 'studentInfo'=>$studentInfo), true); } else { $js_encode = json_encode(array('status'=>FALSE, 'message'=>'There is no record yet.'), true); } header('Content-Type: application/json'); echo $js_encode; break; default: header("HTTP/1.0 405 Method Not Allowed"); break; } ?> |
In this method
getAllStudent()
or getStudent()
from class Student.php
, we will get record(s) into student table.Get All Student Records
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php // getAll Student public function getAllStudent() { try { $sql = "SELECT * FROM student"; $stmt = $this->db->prepare($sql); $stmt->execute(); $result = $stmt->fetchAll(\PDO::FETCH_ASSOC); return $result; } catch (Exception $e) { die("Oh noes! There's an error in the query!"); } } ?> |
Get Student single Record
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php // get Student public function getStudent() { try { $sql = "SELECT * FROM student WHERE id=:student_id"; $stmt = $this->db->prepare($sql); $data = [ 'student_id' => $this->_studentID ]; $stmt->execute($data); $result = $stmt->fetch(\PDO::FETCH_ASSOC); return $result; } catch (Exception $e) { die("Oh noes! There's an error in the query!"); } } ?> |
Step 6: Update Student Record — POST Method
Create PHP file named
student/update.php
to update student records to MySQL database. We will check for POST HTTP request and call method updateStudent()
to update student data to MySQL database table and return JSON response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?php $requestMethod = $_SERVER["REQUEST_METHOD"]; include('../class/Student.php'); $student = new Student(); switch($requestMethod) { case 'POST': $studentID = $_POST['id']; $first_name = $_POST['first_name']; $last_name = $_POST['last_name']; $roll_no = $_POST['roll_no']; $class = $_POST['class']; $age = $_POST['age']; $address = $_POST['address']; $status = $_POST['status']; $student->setStudentID($studentID); $student->setFirstName($first_name); $student->setLastName($last_name); $student->setRollNo($roll_no); $student->setClassName($class); $student->setAge($age); $student->setAddress($address); $studentInfo = $student->updateStudent(); if(!empty($studentInfo)) { $js_encode = json_encode(array('status'=>TRUE, 'message'=>'Student updated Successfully'), true); } else { $js_encode = json_encode(array('status'=>FALSE, 'message'=>'Student updation failed.'), true); } header('Content-Type: application/json'); echo $js_encode; default: header("HTTP/1.0 405 Method Not Allowed"); break; } ?> |
In this method
updateStudent()
from class Student.php
, we will update record into student table.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php // update Student public function updateStudent() { try { $sql = "UPDATE student SET first_name=:first_name, last_name=:last_name, roll_no=:roll_no, class=:class, age=:age, address=:address, status=:status WHERE id=:student_id"; $data = [ 'first_name' => $this->_firstName, 'last_name' => $this->_lastName, 'roll_no' => $this->_rollNo, 'class' => $this->_className, 'age' => $this->_age, 'address' => $this->_address, 'status' => 1, 'student_id' => $this->_studentID ]; $stmt = $this->db->prepare($sql); $stmt->execute($data); $status = $stmt->rowCount(); return $status; } catch (Exception $e) { die("Oh noes! There's an error in the query!"); } } ?> |
Step 7: Delete Student Record from the Database — GET Method
Create PHP file named
student/delete.php
to delete student record to MySQL database. We will check for GET HTTP request and call method deleteStudent()
to delete student data to MySQL database table and return JSON response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php $requestMethod = $_SERVER["REQUEST_METHOD"]; include('../class/Student.php'); $student = new Student(); switch($requestMethod) { case 'GET': $empId = ''; if($_GET['id']) { $studentID = $_GET['id']; $student->setStudentID($studentID); } $studentInfo = $student->deleteStudent(); if(!empty($studentInfo)) { $js_encode = json_encode(array('status'=>TRUE, 'message'=>'Student deleted Successfully.'), true); } else { $js_encode = json_encode(array('status'=>FALSE, 'message'=>'Student delete failed.'), true); } header('Content-Type: application/json'); echo $js_encode; break; default: header("HTTP/1.0 405 Method Not Allowed"); break; } ?> |
In this method
deleteStudent()
from class Student.php
, we will delete record into student table.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php // delete Student public function deleteStudent() { try { $sql = "DELETE FROM student WHERE id=:student_id"; $stmt = $this->db->prepare($sql); $data = [ 'student_id' => $this->_studentID ]; $stmt->execute($data); $status = $stmt->rowCount(); return $status; } catch (Exception $e) { die("Oh noes! There's an error in the query!"); } } ?> |
Step 8: Create .htaccess Rewrite Rule with PHP for Clean URLs
Create student/.htaccess file to write some rule to access rest api with pretty URLs. We will add following rules.
1 2 3 4 5 6 |
RewriteEngine On # Turn on the rewriting engine RewriteRule ^read/([0-9a-zA-Z_-]*)$ read.php?id=$1 [NC,L] RewriteRule ^delete/([0-9]*)$ delete.php?id=$1 [NC,L] RewriteRule ^create create.php [NC,L] RewriteRule ^update update.php [NC,L] |