This php tutorial will show you how to create a rest API without using an API framework. Using this custom framework, we will develop a CRUD rest API. It’s incredibly user-friendly and adaptable.
You can create any file structure or your own PHP framework to suit your needs. Rest api framework allows you to set your own rules and easily access them. There is no requirement to use a framework while creating a Rest API with PHP. Rest APIs can also be created with core PHP code.
If you are more comfortable in watching a video that explains about creating PHP Restful API without Any Rest Framework, then you should watch this video tutorial.
You can use HTTP request methods (GET, POST, PUT, or DELETE) to access the REST API. Rest API provides cross-platform operations that may be accessible by a variety of applications, including web and mobile apps.
A RESTful((Representational State Transfer) API is a design approach for an application program interface (API) that accesses and utilizes data via HTTP requests. That information can be used with the GET, PUT, POST, and DELETE data types, which correspond to activities such as reading, modifying, creating, and removing resources.
There are some of the awesome rest frameworks for PHP are as follows,
Let’s make a rest api example that doesn’t require any PHP framework. I’ll make a folder called 'api/'
. This folder will contain all of the files needed for the rest api tutorial. We’ll make a rest API for the employee module that uses HTTP.
The GET use to Obtain a record, Post is used to create a new record, Put is used to update an existing record, and Delete is used to delete a record from mysql. The rest of the information is as follows:
Route | Method | Type | Posted JSON | Description |
---|---|---|---|---|
/employees | GET | JSON | – | Get all employees data |
/employees/{id} | GET | JSON | – | Get a single employee data |
/employees | POST | JSON | {"employee_name": "Adam", "employee_age": "34", "employee_salary" : "23421"} | Insert new employee record into database |
/employees | PUT | JSON | {"employee_name": "Adam", "employee_age": "34", "employee_salary" : "23421", "id":21} | Update employee record into database |
/employees | DELETE | JSON | {"id" : 59} | Delete particular employee record from database |
I will use the following files for the rest api tutorial,
index.php
: This file is an entry file, This file prevents navigate folder files.connection.php
: This file will use to have a mysql connection string.v1/employees.php
: This file will contain all the rest endpoints and action methods.v1/.htaccess
: This file is used for rest endpoints routing purposes.Create a folder php-api/
in your workspace and add a new file index.php.
Let’s create a table and connection with MySQL. you can create a new database using the following command:
CREATE DATABASE test;
The above command will create a 'test'
database into MySQL server If you already have a MySQL database, please ignore it.
You can create a table within the selected database. Run the following SQL command in SQL query window to create a table called “employee”:
CREATE TABLE IF NOT EXISTS `employee` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'primary key', `employee_name` varchar(255) NOT NULL COMMENT 'employee name', `employee_salary` double NOT NULL COMMENT 'employee salary', `employee_age` int(11) NOT NULL COMMENT 'employee age', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=64 ;
To connect MySQL with PHP using the mysqli connect()
function, we’ll create a file called connection.php
and add the MySQL connection string. In this file, we will add the code below.
<?php Class dbObj{ /* Database connection start */ var $servername = "localhost"; var $username = "root"; var $password = ""; var $dbname = "test"; var $conn; function getConnstring() { $con = mysqli_connect($this->servername, $this->username, $this->password, $this->dbname) or die("Connection failed: " . mysqli_connect_error()); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } else { $this->conn = $con; } return $this->conn; } } ?>
The Parameters are:
$servername
: This will contain the hostname of the database like, IP address or hostname, if your lumen application code and MySQL server are on the same machine. You can define localhost as a hostname.$dbname
: The name of the database. You can replace it as per your db name.$username
: The username of the MySQL database.$password
: The password of the MySQL database.We’ll create a .htaccess file in the v1
folder and write a rule to access the rest API with pretty URLs. In this file, we’ll add the following rules:
RewriteEngine On # Turn on the rewriting engine RewriteRule ^employees/?$ employees.php [NC,L] RewriteRule ^employees/([0-9]+)/?$ employees.php?id=$1 [NC,L]
To get all employee records from MySQL, we’ll develop a GET type HTTP Rest Request. We’ll get data from the employee database with a MySQL query and send a JSON data array to the client as a response object.
Now we’ll create a file called employees.php
in the v1
folder and add a MySQL connection file to access the database table data.
include("../connection.php"); $db = new dbObj(); $connection = $db->getConnstring(); $request_method=$_SERVER["REQUEST_METHOD"];
I have also used $_SERVER method to access action information, like rest requests for add, edit or delete.
We’ll write a PHP switch function to access the correct method in response to an HTTP request (GET, Post, Put, Delete).
switch($request_method) { case 'GET': // Retrive Products if(!empty($_GET["id"])) { $id=intval($_GET["id"]); get_employee($id); } else { get_employees(); } break; default: // Invalid Request Method header("HTTP/1.0 405 Method Not Allowed"); break; }
We’ve made a GET request to get all of the employee data from the MySQL database, We’ve defined the get_employees()
as like below:
function get_employees() { global $connection; $query="SELECT * FROM employee"; $response=array(); $result=mysqli_query($connection, $query); while($row=mysqli_fetch_array($result)) { $response[]=$row; } header('Content-Type: application/json'); echo json_encode($response); }
The mysqli_query()
method fetch data from MySQL employee table and stored as abject into 'result'
variable. The json_encode()
method converts arrays of data into json string.
Now go to http://localhost/v1/employees
URL into your browser to get a list of all employees from the MySQL employee table.
we’ll make an HTTP GET type rest request to get a single employee record from the MySQL database. The employee id is passed to this method as a parameter. it’s the same as the previous method except for employee id parameter.
function get_employee($id=0) { global $connection; $query="SELECT * FROM employee"; if($id != 0) { $query.=" WHERE id=".$id." LIMIT 1"; } $response=array(); $result=mysqli_query($connection, $query); while($row=mysqli_fetch_array($result)) { $response[]=$row; } header('Content-Type: application/json'); echo json_encode($response); }
Now access http://localhost/v1/employees/1
rest API URL from the browser and you will get a single employee record from the MySQL employee table.
We will create a new Rest API to insert a new employee record into MySQL using PHP. I will create a POST type Rest request because We will post some JSON data to the php server.
We will add a new case into the switch method like below:
case 'POST': // Insert Product insert_employee(); break;
Let’s create a insert_employee()
method into the employees.php
file.
function insert_employee() { global $connection; $data = json_decode(file_get_contents('php://input'), true); $employee_name=$data["employee_name"]; $employee_salary=$data["employee_salary"]; $employee_age=$data["employee_age"]; echo $query="INSERT INTO employee SET employee_name='".$employee_name."', employee_salary='".$employee_salary."', employee_age='".$employee_age."'"; if(mysqli_query($connection, $query)) { $response=array( 'status' => 1, 'status_message' =>'Employee Added Successfully.' ); } else { $response=array( 'status' => 0, 'status_message' =>'Employee Addition Failed.' ); } header('Content-Type: application/json'); echo json_encode($response); }
To update data in the MySQL database, we’ll make a new HTTP PUT type Restful api request. Employee id must be given as a parameter for the record to be updated in the employee table.
We will add a new case into the switch method like below:
case 'PUT': // Update Product $id=intval($_GET["id"]); update_employee($id); break;
Now, we will create update_employee()
method into employees.php
file. We will use employee_id
which we want to update and the second is updated data in json format.
function update_employee($id) { global $connection; $post_vars = json_decode(file_get_contents("php://input"),true); $employee_name=$post_vars["employee_name"]; $employee_salary=$post_vars["employee_salary"]; $employee_age=$post_vars["employee_age"]; $query="UPDATE employee SET employee_name='".$employee_name."', employee_salary='".$employee_salary."', employee_age='".$employee_age."' WHERE id=".$id; if(mysqli_query($connection, $query)) { $response=array( 'status' => 1, 'status_message' =>'Employee Updated Successfully.' ); } else { $response=array( 'status' => 0, 'status_message' =>'Employee Updation Failed.' ); } header('Content-Type: application/json'); echo json_encode($response); }
We have taken employee_id
as a param and json data to updated record into mysql table, if everything fine then send ‘updated message’ otherwise send error message.
We will create a new DELETE Type restful API request using PHP to remove employee records from the MySQL database. We will pass employee_id as a parameter that you want to delete from the employee table.
We will add new case into switch method like below,
case 'DELETE': // Delete Product $id=intval($_GET["id"]); delete_employee($id); break;
Now we will create delete_employee()
method into employees.php
file.We will use employee_id
which we want to delete record from employee table.
function delete_employee($id) { global $connection; $query="DELETE FROM employee WHERE id=".$id; if(mysqli_query($connection, $query)) { $response=array( 'status' => 1, 'status_message' =>'Employee Deleted Successfully.' ); } else { $response=array( 'status' => 0, 'status_message' =>'Employee Deletion Failed.' ); } header('Content-Type: application/json'); echo json_encode($response); }
We built a restful API that allows you to access all employees, a single employee record, add new employee entries, change employee data, and delete employee data from the MySQL database. You can add security-related features like tokens to prevent unauthorized users from accessing the rest API.
This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More
in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More
This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More
We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More
in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More
I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More
View Comments
Great helper dude. ;)
The code you have given relies on input file. Since I am new to REST api can you please suggest edits to your code that would allow it to work when sending request using postman or other API testers. Thanks.
You can use using postman like, hostname//employees , I have added .htaccess to access from rest client
Great but how to add Authorization: Bearer to this?
Hey, You can add and tell to others :)
Nice article :)
GREAT!
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /var/www/vhosts/htm.kz/httpdocs/V1/employees.php on line 33
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in /var/www/vhosts/htm.kz/httpdocs/V1/employees.php on line 34
I am not sure, It might be db connection issue.
For your GET methods, use mysqli_fetch_assoc() instead of mysqli_fetch_array(). The JSON will be much more legible.
thanks for your suggestion
I have read your blog on create RESTful APIs with PHP. It was very interesting and helpful but I can add some extra points in your article. Here some extra points:
1.Create a database and DB table.
2.Establish database connection.
3.Create a REST API file. Create index or HTML file. Fetch the records from database via cURL.
thanks, i ll do