How to Implement PHP REST API to Connect Different Applications Easily

0
Shares
How to Implement PHP REST API to Connect Different Applications Easily
5 (100%) 4 votes

In today’s world, different applications on different devices are connected to one another and main reason for it is APIs. Now, before getting into the subject of PHP REST API implementation process, let’s first see what really PHP REST API is.

What is PHP REST API?

REST stands for Representational State Transfer and it means that the request and the response should contain a representation of the information. This means, the requests must use proper HTTP methods and the response must be in a proper format, instead of just text.

In this PHP REST API tutorial, we’ll see the complete implementation process of PHP REST API in web application demo.

Let’s Get Started

From below code define REST API class file.

require_once("Rest.inc.php");

When you want to use REST API, include the above class of REST.

Now, let’s move forward on how to use REST API.

API.php

class API extends REST { // here define api class with extents of REST.


public $data = "";

const DB_SERVER = "localhost";
const DB_USER = "{username}";
const DB_PASSWORD = "{password}";
const DB = "{database name}";

private $db = NULL;

// create constructor of class for defined of object.
public function __construct()
{
parent::__construct(); // Init parent contructor
$this->dbConnect(); // Initiate Database connection
}

/*
* Database connection
*/
private function dbConnect(){
$this->db = mysql_connect(
self::DB_SERVER,self::DB_USER,self::DB_PASSWORD
);
if($this->db)
mysql_select_db(self::DB,$this->db);
}

/*
* Public method for access api.
* This method dynamically call the method based on the query string
*
*/
public function processApi(){
$func = strtolower(trim(str_replace("/","",$_REQUEST['request'])));
if((int)method_exists($this,$func) > 0)
$this->$func();
else
$this->response('',404); // If the method not exist with in this class, response would be "Page not found".
}

How to Create Action of API?

To create login action, write the below code.

private function login(){
// Cross validation if the request method is POST else it will return "Not Acceptable" status
if($this->get_request_method() != "POST"){
$this->response('',406);
}

$email = $this->_request['email'];
$password = $this->_request['pwd'];

// Input validations
if(!empty($email) and !empty($password)){
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
$sql = mysql_query("SELECT user_id, user_fullname, user_email FROM users WHERE user_email = '$email' AND user_password = '".md5($password)."' LIMIT 1", $this->db);
if(mysql_num_rows($sql) > 0){
$result = mysql_fetch_array($sql,MYSQL_ASSOC);

// If success everything is good send header as "OK" and user details
$this->response($this->json($result), 200);
}
$this->response('', 204); // If no records "No Content" status
}
}

// If invalid inputs "Bad Request" status message and reason
$error = array('status' => "Failed", "msg" => "Invalid Email address or Password");
$this->response($this->json($error), 400);
}

To Access login API in postman tool go to Http://localhost/rest/api.php/login.

How to Convert Array or Object in JSON?

/*
* Encode array into JSON
*/
private function json($data){
if(is_array($data)){
return json_encode($data);
}
}

To add action for Additional View, write following code.

private function users(){
// Cross validation if the request method is GET else it will return "Not Acceptable" status
if($this->get_request_method() != "GET"){
$this->response('',406);
}
$sql = mysql_query("SELECT user_id, user_fullname, user_email FROM users WHERE user_status = 1", $this->db);
if(mysql_num_rows($sql) > 0){
$result = array();
while($rlt = mysql_fetch_array($sql,MYSQL_ASSOC)){
$result[] = $rlt;
}
// If success everythig is good send header as "OK" and return list of users in JSON format
$this->response($this->json($result), 200);
}
$this->response('',204); // If no records "No Content" status
}

private function deleteUser(){
// Cross validation if the request method is DELETE else it will return "Not Acceptable" status
if($this->get_request_method() != "DELETE"){
$this->response('',406);
}
$id = (int)$this->_request['id'];
if($id > 0){
mysql_query("DELETE FROM users WHERE user_id = $id");
$success = array('status' => "Success", "msg" => "Successfully one record deleted.");
$this->response($this->json($success),200);
}else
$this->response('',204); // If no records "No Content" status
}

/*
* Encode array into JSON
*/
private function json($data){
if(is_array($data)){
return json_encode($data);
}
}
}

Below is the Entire code of API.php

API.php

<?php

require_once("Rest.inc.php");

class API extends REST {

public $data = "";

const DB_SERVER = "localhost";
const DB_USER = "root";
const DB_PASSWORD = "ur48x";
const DB = "restfulldemo";

private $db = NULL;

public function __construct(){
parent::__construct(); // Init parent contructor
$this->dbConnect(); // Initiate Database connection
}

/*
* Database connection
*/
private function dbConnect(){
$this->db = mysql_connect(self::DB_SERVER,self::DB_USER,self::DB_PASSWORD);
if($this->db)
mysql_select_db(self::DB,$this->db);
}

/*
* Public method for access api.
* This method dynmically call the method based on the query string
*
*/
public function processApi(){
$func = strtolower(trim(str_replace("/","",$_REQUEST['rquest'])));
if((int)method_exists($this,$func) > 0)
$this->$func();
else
$this->response('',404); // If the method not exist with in this class, response would be "Page not found".
}

/*
* Simple login API
* Login must be POST method
* email : <USER EMAIL>
* pwd : <USER PASSWORD>
*/

private function login(){
// Cross validation if the request method is POST else it will return "Not Acceptable" status
if($this->get_request_method() != "POST"){
$this->response('',406);
}

$email = $this->_request['email'];
$password = $this->_request['pwd'];

// Input validations
if(!empty($email) and !empty($password)){
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
$sql = mysql_query("SELECT user_id, user_fullname, user_email FROM users WHERE user_email = '$email' AND user_password = '".md5($password)."' LIMIT 1", $this->db);
if(mysql_num_rows($sql) > 0){
$result = mysql_fetch_array($sql,MYSQL_ASSOC);

// If success everythig is good send header as "OK" and user details
$this->response($this->json($result), 200);
}
$this->response('', 204); // If no records "No Content" status
}
}

// If invalid inputs "Bad Request" status message and reason
$error = array('status' => "Failed", "msg" => "Invalid Email address or Password");
$this->response($this->json($error), 400);
}

private function users(){
// Cross validation if the request method is GET else it will return "Not Acceptable" status
if($this->get_request_method() != "GET"){
$this->response('',406);
}
$sql = mysql_query("SELECT user_id, user_fullname, user_email FROM users WHERE user_status = 1", $this->db);
if(mysql_num_rows($sql) > 0){
$result = array();
while($rlt = mysql_fetch_array($sql,MYSQL_ASSOC)){
$result[] = $rlt;
}
// If success everythig is good send header as "OK" and return list of users in JSON format
$this->response($this->json($result), 200);
}
$this->response('',204); // If no records "No Content" status
}

private function deleteUser(){
// Cross validation if the request method is DELETE else it will return "Not Acceptable" status
if($this->get_request_method() != "DELETE"){
$this->response('',406);
}
$id = (int)$this->_request['id'];
if($id > 0){
mysql_query("DELETE FROM users WHERE user_id = $id");
$success = array('status' => "Success", "msg" => "Successfully one record deleted.");
$this->response($this->json($success),200);
}else
$this->response('',204); // If no records "No Content" status
}

/*
* Encode array into JSON
*/
private function json($data){
if(is_array($data)){
return json_encode($data);
}
}
}

// Initiiate Library

$api = new API;
$api->processApi();
?>

That’s it!

Now, of course there is lot more to REST APIs than what we just did here. And, if you’re looking for opportunities to explore the PHP REST API and implement it in your web application, Hire PHP developer to understand the working of PHP REST API and implement it in your PHP web development project.

This page was last edited on May 11th, 2017, at 15:31.
 
0
Shares
 

Have a Startup Mobile App Idea in Mind? Let's Discuss!

Get your free consultation now