PHP REST API backed up with a MySQL database is a very common schematic of an Enterprise mobile application.
The most important concept in REST is resources, which are identified by global IDs — typically using URIs. Client applications use HTTP methods (GET/ POST/ PUT/ DELETE) to manipulate the resource or collection of resources. A RESTful Web service is implemented using HTTP and the principles of REST.
Methods
HTTP methods are mapped to CRUD (create, read, update and delete) actions for a resource. Although you can make slight modifications such as making the PUT method to create or update, the basic patterns are listed as follows.
HTTP GET: Get/List/Retrieve an individual resource or a collection of resources.
HTTP POST: Create a new resource or resources.
HTTP PUT: Update an existing resource or collection of resources.
HTTP DELETE: Delete a resource or collection of resources.
db.php
Here in db.php we simply creates database connection.
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
/**
* DB Connection
*/
class DB
{
const DB_SERVER = "localhost";
const DB_USER = "root";
const DB_PASSWORD = "";
const DB = "webservices";
public $con = NULL;
public function __construct()
{
$this->dbConnect();// Initiate Database connection
}
//Database connection
private function dbConnect()
{
$this->con = mysqli_connect(self::DB_SERVER,self::DB_USER,self::DB_PASSWORD,self::DB);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
}
?>
|
Rest.php
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
|
<?php
include('db.php');
class REST extends DB {
public $_content_type = "application/json";
public $_request = array();
private $_code = 200;
public function __construct(){
parent::__construct();
$this->inputs();
}
// returning response with HTTP status code and headers
public function response($data,$statusCode){
$this->_code = ($statusCode)?$statusCode:200;
$this->setHeaders();
echo $data;
exit;
}
// HTTP messages with status code
private function getStatusMessage(){
$status = array(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => '(Unused)',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported');
return ($status[$this->_code])?$status[$this->_code]:$status[500];
}
// receiving inputs in json and decoding the input
public function inputs(){
$json = file_get_contents('php://input');
$this->_request = json_decode($json);
}
// set HTTP headers
private function setHeaders(){
header("HTTP/1.1 ".$this->_code." ".$this->getStatusMessage());
header("Content-Type:".$this->_content_type);
}
//Encode array into JSON
protected function json($data,$message,$statusCode,$status)
{
if(is_array($data)){
$response = array();
$response['status'] = $status;
$response['statusCode'] = $statusCode;
$response['message'] = $message;
$response['result'] = $data;
return json_encode($response);
}
}
// Function for authenticating the api request
protected function checkAuth(){
$headers = apache_request_headers();
// here you can check access toke of perticular user as well from db
if(!empty($headers['AccessToken']) && $headers['AccessToken']=='$2y$10$QI49JvNHcVJbldi9KMCBeeNRxatK/XVYUNgyL2HsG1HR4RiPyayDq'){
return true;
}else{
$this->response($this->json([],'Unauthorized request',401,0), 401);
}
}
}
?>
|
Rest.php is the common file which will be used in every api page. In Rest.php I have created set of HTTP status codes with messages which I'm using when I'm returning the JSON response. We have a function to get the inputs and set the headers of response. I also have created a function checkAuth() to validate the API request. Currently I have used hard coded access token you can change it according to your need. We also have a function json() which set the response array and decode it to JSON.
api.php
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
|
<?php
include('Rest.php');
class Api extends REST{
public $data = "";
public function __construct()
{
parent::__construct();
}
//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->checkAuth()==true)
$this->$func();
else
$this->response($this->json([],'Route not found',404,0), 404);
// If the method not exist with in this class, response would be "Page not found".
}
// function to save order details
public function saveDetails(){
$nameErr = $productIdErr = $emailErr = '';
$status = 0;
$statusCode = 400;
if(empty($this->_request->name)){
$nameErr = 'Name is required';
}else{
$name = htmlspecialchars($this->_request->name);
}
if(empty($this->_request->productId)){
$productIdErr = 'Product id is required';
}else{
$productId = htmlspecialchars($this->_request->productId);
}
if(empty($this->_request->email)){
$emailErr = 'Email id is required';
}else{
$email = htmlspecialchars($this->_request->email);
}
if($nameErr != ''){
$message = $nameErr;
}
elseif($productIdErr != ''){
$message = $productIdErr;
}
elseif($emailErr != ''){
$message = $emailErr;
}
else{
$age = !empty($this->_request->age) ? htmlspecialchars($this->_request->age) : '';
$company = !empty($this->_request->company) ? htmlspecialchars($this->_request->company) : '';
$address = !empty($this->_request->address) ? htmlspecialchars($this->_request->address) : '';
$mobile = !empty($this->_request->mobile) ? htmlspecialchars($this->_request->mobile) : '';
$height = !empty($this->_request->height) ? htmlspecialchars($this->_request->height) : '';
$weight = !empty($this->_request->weight) ? htmlspecialchars($this->_request->weight) : '';
$sql = "INSERT into detail (name,age,product_id,company,address,mobile,email,height,weight)
VALUES('".$name."','".$age."','".$productId."','".$company."','".$address."','".$mobile."','".$email."','".$height."','".$weight."')";
$result = $this->con->query($sql);
if($result){
$status = 1;
$statusCode = 200;
}
$message = 'Details saved';
}
$this->response($this->json([],$message,$statusCode,$status), $statusCode);
}
// function to get products
public function getProducts(){
// install mamche before using it
// sudo apt-get install memcached
// sudo pecl install memcache
// $memcacheObj = new Memcache;
// memcache host : localhost
// memcache port : 11211
// $memcacheObj->connect('localhost',11211) or die('Memcache could not connect');
$cacheResults = array();
$products = array();
// $cacheResults = $memcacheObj->get('products');
if(!empty($cacheResults)){
$products = $cacheResults;
}
else{
$sql = "SELECT id,product_name FROM products";
$result = $this->con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$products[] = $row;
}
// cache 5 minutes or 300 seconds
// $memcacheObj->set('products',$products,MEMCACHE_COMPRESSED, 300);
}
}
$this->response($this->json($products,'Products List',200,1), 200);
}
}
// Initiiate Library
$api = new Api;
$api->processApi();
?>
|
For saving products:
Request URL: http://localhost/core/restful-api-php/saveDetails
Method : POST
Headers: { "AccessToken" : "$2y$10$QI49JvNHcVJbldi9KMCBeeNRxatK/XVYUNgyL2HsG1HR4RiPyayDq", "Content-Type" : "application/json" }
Body: {
"name" : "Coding 4 Developers",
"productId" : 1,
"email" : "info@www.coding4developers.com",
"age" : 27,
"company" : "Coding 4 Developers",
"address" : "Bulandshahr UP",
"mobile" : 6566564,
"height" : 5454,
"weight" : 545
}
For fetching products list:
Request URL: http://localhost/core/restful-api-php/getProducts
Method : POST
Headers: { "AccessToken" : "$2y$10$QI49JvNHcVJbldi9KMCBeeNRxatK/XVYUNgyL2HsG1HR4RiPyayDq" }
.htaccess
1
2
3
4
5
6
7
8
9
10
11
12
|
<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>
|
how i solve Notice: Undefined index: request in C:\xampp\htdocs\restful-api-php-master\restful-api-php-master\api.php on line 16
{"status":0,"statusCode":404,"message":"Route not found","result":[]}
Thanks for ones marvelous posting! I definitely enjoyed reading it,
you can be a great author. I will always bookmark your blog and
will come back in the future. I want to encourage
that you continue your great writing, have a nice holiday weekend!