Create PHP Restful API without Any Rest Framework Dependency

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.

Video Tutorial

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.

What’s Rest API

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,

Reastful API Using PHP and MySQL

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:

RouteMethodTypePosted JSONDescription
/employeesGETJSONGet all employees data
/employees/{id}GETJSONGet a single employee data
/employeesPOSTJSON{"employee_name": "Adam", "employee_age": "34", "employee_salary" : "23421"}Insert new employee record into database
/employeesPUTJSON{"employee_name": "Adam", "employee_age": "34", "employee_salary" : "23421", "id":21}Update employee record into database
/employeesDELETEJSON{"id" : 59}Delete particular employee record from database

I will use following files for this rest api tutorial,

  1. index.php: This file is an entry file, This file prevents navigate folder files.
  2. connection.php: This file will use to have a mysql connection string.
  3. v1/employees.php: This file will contain all the rest endpoints and action methods.
  4. v1/.htaccess: This file is used for rest endpoints routing purposes.

Employee table Schema

Create a 'test' MySQL database, If you already have a MySQL database, perform the following sql in that database’s SQL query window to create a table:

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 ;

MySQL Database Connection With PHP using MySQLi

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 hostname of 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 database. can replace as per your db name.
  • $username: The username of the MySQL database.
  • $password: The password of the MySQL database.

.htaccess Rewriterule with PHP for Clean URLs

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]

Restful API to fetch all records from MySQL

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.

Restful Api to get a single record from MySQL using PHP

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.

Rest Api to Create New Record into MySQL

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);
	}

Rest API to Update Record into MySQL using PHP

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.

Rest API to delete Record from MySQL

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);
}

Conclusions:

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.

11 thoughts on “Create PHP Restful API without Any Rest Framework Dependency

  1. 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.

  2. 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

  3. For your GET methods, use mysqli_fetch_assoc() instead of mysqli_fetch_array(). The JSON will be much more legible.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.