Ads

May 12, 2013

Create a RESTful Services API in PHP


Are you working with multiple devices like iPhone, Android and Web then take a look at this post that explains you how to develop a RESTful API in PHP.  Representational state transfer (REST) is a software system for distributing the data to different kind of applications. The web service system produce status code response in JSON or XML format.

Create a RESTful Services API in PHP.

Download Script

Developer
Arun Kumar Shekar
Arun Kumar Sekar
Engineer
Chennai, INDIA

Database
Sample database users table columns user_id, user_fullname, user_email, user_password and user_status.
CREATE TABLE IF NOT EXISTS `users`
(
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_fullname` varchar(25) NOT NULL,
`user_email` varchar(50) NOT NULL,
`user_password` varchar(50) NOT NULL,
`user_status` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Rest API Class: api.php
Contains simple PHP code, here you have to modify database configuration details like database name, username and password.
<?php
require_once("Rest.inc.php");

class API extends REST
{
public $data = "";
const DB_SERVER = "localhost";
const DB_USER = "Database_Username";
const DB_PASSWORD = "Database_Password";
const DB = "Database_Name";

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".
}

private function login()
{
..............
}

private function users()
{
..............
}

private function deleteUser()
{
.............
}

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

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

Login POST
Displaying users records from the users table Rest API URL http://localhost/rest/login/. This Restful API login status works with status codes if status code 200 login success else status code 204 shows fail message. For more status code information check Rest.inc.php in download script.
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);
}

Users GET
Displaying users records from the users table Rest API URL http://localhost/rest/users/
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
}

DeleteUser
Delete user function based on the user_id value deleting the particular record from the users table Rest API URL http://localhost/rest/deleteUser/
private function deleteUser()
{

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

Chrome Extention
A Extention for testing PHP restful API response download here Advanced REST client Application

.htaccess code
Rewriting code for friendly URLs. In the download code you just modify htaccess.txt to .htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^(.*)$ api.php?rquest=$1 [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ api.php [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^(.*)$ api.php [QSA,NC,L]
</IfModule>

2 comments:

Anonymous said...

hmmmm, nice thnx for share

Unknown said...

Do you have a private API example? With the method's name hidden in a json?

Most Popular Posts