Create a RESTful Services API in PHP


SUBMITTED BY: Guest

DATE: May 3, 2013, 4:23 p.m.

FORMAT: PHP

SIZE: 5.6 kB

HITS: 1245

  1. Database
  2. Sample database users table columns user_id, user_fullname, user_email, user_password and user_status.
  3. CREATE TABLE IF NOT EXISTS `users`
  4. (
  5. `user_id` int(11) NOT NULL AUTO_INCREMENT,
  6. `user_fullname` varchar(25) NOT NULL,
  7. `user_email` varchar(50) NOT NULL,
  8. `user_password` varchar(50) NOT NULL,
  9. `user_status` tinyint(1) NOT NULL DEFAULT '0',
  10. PRIMARY KEY (`user_id`)
  11. ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
  12. Rest API Class: api.php
  13. Contains simple PHP code, here you have to modify database configuration details like database name, username and password.
  14. <?php
  15. require_once("Rest.inc.php");
  16. class API extends REST
  17. {
  18. public $data = "";
  19. const DB_SERVER = "localhost";
  20. const DB_USER = "Database_Username";
  21. const DB_PASSWORD = "Database_Password";
  22. const DB = "Database_Name";
  23. private $db = NULL;
  24. public function __construct()
  25. {
  26. parent::__construct();// Init parent contructor
  27. $this->dbConnect();// Initiate Database connection
  28. }
  29. //Database connection
  30. private function dbConnect()
  31. {
  32. $this->db = mysql_connect(self::DB_SERVER,self::DB_USER,self::DB_PASSWORD);
  33. if($this->db)
  34. mysql_select_db(self::DB,$this->db);
  35. }
  36. //Public method for access api.
  37. //This method dynmically call the method based on the query string
  38. public function processApi()
  39. {
  40. $func = strtolower(trim(str_replace("/","",$_REQUEST['rquest'])));
  41. if((int)method_exists($this,$func) > 0)
  42. $this->$func();
  43. else
  44. $this->response('',404);
  45. // If the method not exist with in this class, response would be "Page not found".
  46. }
  47. private function login()
  48. {
  49. ..............
  50. }
  51. private function users()
  52. {
  53. ..............
  54. }
  55. private function deleteUser()
  56. {
  57. .............
  58. }
  59. //Encode array into JSON
  60. private function json($data)
  61. {
  62. if(is_array($data)){
  63. return json_encode($data);
  64. }
  65. }
  66. }
  67. // Initiiate Library
  68. $api = new API;
  69. $api->processApi();
  70. ?>
  71. Login POST
  72. 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.
  73. private function login()
  74. {
  75. // Cross validation if the request method is POST else it will return "Not Acceptable" status
  76. if($this->get_request_method() != "POST")
  77. {
  78. $this->response('',406);
  79. }
  80. $email = $this->_request['email'];
  81. $password = $this->_request['pwd'];
  82. // Input validations
  83. if(!empty($email) and !empty($password))
  84. {
  85. if(filter_var($email, FILTER_VALIDATE_EMAIL)){
  86. $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);
  87. if(mysql_num_rows($sql) > 0){
  88. $result = mysql_fetch_array($sql,MYSQL_ASSOC);
  89. // If success everythig is good send header as "OK" and user details
  90. $this->response($this->json($result), 200);
  91. }
  92. $this->response('', 204); // If no records "No Content" status
  93. }
  94. }
  95. // If invalid inputs "Bad Request" status message and reason
  96. $error = array('status' => "Failed", "msg" => "Invalid Email address or Password");
  97. $this->response($this->json($error), 400);
  98. }
  99. Users GET
  100. Displaying users records from the users table Rest API URL http://localhost/rest/users/
  101. private function users()
  102. {
  103. // Cross validation if the request method is GET else it will return "Not Acceptable" status
  104. if($this->get_request_method() != "GET")
  105. {
  106. $this->response('',406);
  107. }
  108. $sql = mysql_query("SELECT user_id, user_fullname, user_email FROM users WHERE user_status = 1", $this->db);
  109. if(mysql_num_rows($sql) > 0)
  110. {
  111. $result = array();
  112. while($rlt = mysql_fetch_array($sql,MYSQL_ASSOC))
  113. {
  114. $result[] = $rlt;
  115. }
  116. // If success everythig is good send header as "OK" and return list of users in JSON format
  117. $this->response($this->json($result), 200);
  118. }
  119. $this->response('',204); // If no records "No Content" status
  120. }
  121. DeleteUser
  122. Delete user function based on the user_id value deleting the particular record from the users table Rest API URL http://localhost/rest/deleteUser/
  123. private function deleteUser()
  124. {
  125. if($this->get_request_method() != "DELETE"){
  126. $this->response('',406);
  127. }
  128. $id = (int)$this->_request['id'];
  129. if($id > 0)
  130. {
  131. mysql_query("DELETE FROM users WHERE user_id = $id");
  132. $success = array('status' => "Success", "msg" => "Successfully one record deleted.");
  133. $this->response($this->json($success),200);
  134. }
  135. else
  136. {
  137. $this->response('',204); // If no records "No Content" status
  138. }
  139. }
  140. Chrome Extention
  141. A Extention for testing PHP restful API response download here Advanced REST client Application
  142. .htaccess code
  143. Rewriting code for friendly URLs. In the download code you just modify htaccess.txt to .htaccess
  144. <IfModule mod_rewrite.c>
  145. RewriteEngine On
  146. RewriteCond %{REQUEST_FILENAME} !-d
  147. RewriteCond %{REQUEST_FILENAME} !-s
  148. RewriteRule ^(.*)$ api.php?rquest=$1 [QSA,NC,L]
  149. RewriteCond %{REQUEST_FILENAME} -d
  150. RewriteRule ^(.*)$ api.php [QSA,NC,L]
  151. RewriteCond %{REQUEST_FILENAME} -s
  152. RewriteRule ^(.*)$ api.php [QSA,NC,L]
  153. </IfModule>

comments powered by Disqus