In last post we were using PHP Rest API Framework SLIM to create a simple REST API for our android application. In the last post I have created the student registration and student login part. Now in this post we will complete our REST API.
If you haven’t gone through the last PHP Rest API Framework Tutorial, then you should first check that. You can go to my last PHP Rest API Framework tutorial from the link given below.
PHP Restful API Framework SLIM to Create REST API – 1
In the last post I have already explained the codes. So I will not be explaining codes here. We will add more codes only. But before showing you the codes I will show you the final API that is already created.
The final REST API
In the below table you can see all the URL paths with the request method and required parameters.
URL | Method | Parameters |
---|---|---|
/createstudent | POST | name, username, password |
/studentlogin | POST | username, password |
/createfaculty | POST | name, username, password, subject |
/facultylogin | POST | username, password |
/createassignment | POST | name, details, facultyid, studentid |
/assignments/:id | GET | student api key |
/students | GET | faculty api key |
/submitassignment/:id | PUT | faculty api key |
I am using wamp server and the location to my API Â is.
http://localhost/StudentApp/v1
Response of Requests
These are the success response of every call.
http://localhost/StudentApp/v1/createstudent
1 2 3 4 5 6 |
{ "error":false, "message":"You are successfully registered" } |
http://localhost/StudentApp/v1/studentlogin
1 2 3 4 5 6 7 8 9 |
{ "error":false, "id":2, "name":"Belal Khan", "username":"probelalkhan", "apikey":"589d3d5ad22808e7cb54fd1ee2affd3c" } |
http://localhost/StudentApp/v1/createfaculty
1 2 3 4 5 6 |
{ "error":false, "message":"You are successfully registered" } |
http://localhost/StudentApp/v1/facultylogin
1 2 3 4 5 6 7 8 9 10 |
{ "error":false, "id":1, "name":"Ritesh Kumar", "username":"ritesh", "subject":"DBMS", "apikey":"acb4e1a9e78d3f0aab873d9f89c7472f" } |
http://localhost/StudentApp/v1/createassignment
1 2 3 4 5 6 |
{ "error":false, "message":"Assignment created successfully" } |
http://localhost/StudentApp/v1/assignments/2
In the above URL 2 is the student id.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
{ Â Â Â "error": false, Â Â Â "assignments": [ Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â "id": 3, Â Â Â Â Â Â Â Â Â "name": "Business Management", Â Â Â Â Â Â Â Â Â "details": "Discuss role of IT in HRM", Â Â Â Â Â Â Â Â Â "completed": 0, Â Â Â Â Â Â Â Â Â "faculty": "Ritesh Kumar" Â Â Â Â Â Â }, Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â "id": 4, Â Â Â Â Â Â Â Â Â "name": "C++", Â Â Â Â Â Â Â Â Â "details": "Create a simple login app using c++", Â Â Â Â Â Â Â Â Â "completed": 0, Â Â Â Â Â Â Â Â Â "faculty": "Ritesh Kumar" Â Â Â Â Â Â } Â Â Â ] } |
http://localhost/StudentApp/v1/students
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
{ Â Â Â "error": false, Â Â Â "students": [ Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â "id": 1, Â Â Â Â Â Â Â Â Â "name": "belal", Â Â Â Â Â Â Â Â Â "username": "belal" Â Â Â Â Â Â }, Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â "id": 2, Â Â Â Â Â Â Â Â Â "name": "Belal Khan", Â Â Â Â Â Â Â Â Â "username": "probelalkhan" Â Â Â Â Â Â }, Â Â Â Â Â Â { Â Â Â Â Â Â Â Â Â "id": 3, Â Â Â Â Â Â Â Â Â "name": "Vivek Raj", Â Â Â Â Â Â Â Â Â "username": "vivek" Â Â Â Â Â Â } Â Â Â ] } |
http://localhost/StudentApp/v1/submitassignment/3
Here 3 is the assignment id.
1 2 3 4 5 6 |
{ "error":false, "message":"Assignment submitted successfully" } |
Updating the Existing Code
So I explained the whole API, now its time to write code to create the above explained API. So the main modification (actually addition of codes) will be done on DbOperation.php and index.php files.
So first come to DbOperation.php and write the following code.
Updating DbOperation.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 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 |
<?php class DbOperation { private $con; function __construct() { require_once dirname(__FILE__) . '/DbConnect.php'; $db = new DbConnect(); $this->con = $db->connect(); } //Method to register a new student public function createStudent($name,$username,$pass){ if (!$this->isStudentExists($username)) { $password = md5($pass); $apikey = $this->generateApiKey(); $stmt = $this->con->prepare("INSERT INTO students(name, username, password, api_key) values(?, ?, ?, ?)"); $stmt->bind_param("ssss", $name, $username, $password, $apikey); $result = $stmt->execute(); $stmt->close(); if ($result) { return 0; } else { return 1; } } else { return 2; } } //Method to let a student log in public function studentLogin($username,$pass){ $password = md5($pass); $stmt = $this->con->prepare("SELECT * FROM students WHERE username=? and password=?"); $stmt->bind_param("ss",$username,$password); $stmt->execute(); $stmt->store_result(); $num_rows = $stmt->num_rows; $stmt->close(); return $num_rows>0; } //method to register a new facultly public function createFaculty($name,$username,$pass,$subject){ if (!$this->isFacultyExists($username)) { $password = md5($pass); $apikey = $this->generateApiKey(); $stmt = $this->con->prepare("INSERT INTO faculties(name, username, password, subject, api_key) values(?, ?, ?, ?, ?)"); $stmt->bind_param("sssss", $name, $username, $password, $subject, $apikey); $result = $stmt->execute(); $stmt->close(); if ($result) { return 0; } else { return 1; } } else { return 2; } } //method to let a faculty log in public function facultyLogin($username, $pass){ $password = md5($pass); $stmt = $this->con->prepare("SELECT * FROM faculties WHERE username=? and password =?"); $stmt->bind_param("ss",$username,$password); $stmt->execute(); $stmt->store_result(); $num_rows = $stmt->num_rows; $stmt->close(); return $num_rows>0; } //Method to create a new assignment public function createAssignment($name,$detail,$facultyid,$studentid){ $stmt = $this->con->prepare("INSERT INTO assignments (name,details,faculties_id,students_id) VALUES (?,?,?,?)"); $stmt->bind_param("ssii",$name,$detail,$facultyid,$studentid); $result = $stmt->execute(); $stmt->close(); if($result){ return true; } return false; } //Method to update assignment status public function updateAssignment($id){ $stmt = $this->con->prepare("UPDATE assignments SET completed = 1 WHERE id=?"); $stmt->bind_param("i",$id); $result = $stmt->execute(); $stmt->close(); if($result){ return true; } return false; } //Method to get all the assignments of a particular student public function getAssignments($studentid){ $stmt = $this->con->prepare("SELECT * FROM assignments WHERE students_id=?"); $stmt->bind_param("i",$studentid); $stmt->execute(); $assignments = $stmt->get_result(); $stmt->close(); return $assignments; } //Method to get student details public function getStudent($username){ $stmt = $this->con->prepare("SELECT * FROM students WHERE username=?"); $stmt->bind_param("s",$username); $stmt->execute(); $student = $stmt->get_result()->fetch_assoc(); $stmt->close(); return $student; } //Method to fetch all students from database public function getAllStudents(){ $stmt = $this->con->prepare("SELECT * FROM students"); $stmt->execute(); $students = $stmt->get_result(); $stmt->close(); return $students; } //Method to get faculy details by username public function getFaculty($username){ $stmt = $this->con->prepare("SELECT * FROM faculties WHERE username=?"); $stmt->bind_param("s",$username); $stmt->execute(); $faculty = $stmt->get_result()->fetch_assoc(); $stmt->close(); return $faculty; } //Method to get faculty name by id public function getFacultyName($id){ $stmt = $this->con->prepare("SELECT name FROM faculties WHERE id=?"); $stmt->bind_param("i",$id); $stmt->execute(); $faculty = $stmt->get_result()->fetch_assoc(); $stmt->close(); return $faculty['name']; } //Method to check the student username already exist or not private function isStudentExists($username) { $stmt = $this->con->prepare("SELECT id from students WHERE username = ?"); $stmt->bind_param("s", $username); $stmt->execute(); $stmt->store_result(); $num_rows = $stmt->num_rows; $stmt->close(); return $num_rows > 0; } //Method to check the faculty username already exist or not private function isFacultyExists($username) { $stmt = $this->con->prepare("SELECT id from faculties WHERE username = ?"); $stmt->bind_param("s", $username); $stmt->execute(); $stmt->store_result(); $num_rows = $stmt->num_rows; $stmt->close(); return $num_rows > 0; } //Checking the student is valid or not by api key public function isValidStudent($api_key) { $stmt = $this->con->prepare("SELECT id from students WHERE api_key = ?"); $stmt->bind_param("s", $api_key); $stmt->execute(); $stmt->store_result(); $num_rows = $stmt->num_rows; $stmt->close(); return $num_rows > 0; } //Checking the faculty is valid or not by api key public function isValidFaculty($api_key){ $stmt = $this->con->prepare("SELECT id from faculties WHERE api_key=?"); $stmt->bind_param("s",$api_key); $stmt->execute(); $stmt->store_result(); $num_rows = $stmt->num_rows; $stmt->close(); return $num_rows>0; } //Method to generate a unique api key every time private function generateApiKey(){ return md5(uniqid(rand(), true)); } } |
Updating index.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 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 |
<?php //including the required files require_once '../include/DbOperation.php'; require '.././libs/Slim/Slim.php'; \Slim\Slim::registerAutoloader(); $app = new \Slim\Slim(); /* * * URL: http://localhost/StudentApp/v1/createstudent * Parameters: name, username, password * Method: POST * */ $app->post('/createstudent', function () use ($app) { verifyRequiredParams(array('name', 'username', 'password')); $response = array(); $name = $app->request->post('name'); $username = $app->request->post('username'); $password = $app->request->post('password'); $db = new DbOperation(); $res = $db->createStudent($name, $username, $password); if ($res == 0) { $response["error"] = false; $response["message"] = "You are successfully registered"; echoResponse(201, $response); } else if ($res == 1) { $response["error"] = true; $response["message"] = "Oops! An error occurred while registereing"; echoResponse(200, $response); } else if ($res == 2) { $response["error"] = true; $response["message"] = "Sorry, this student already existed"; echoResponse(200, $response); } }); /* * * URL: http://localhost/StudentApp/v1/studentlogin * Parameters: username, password * Method: POST * */ $app->post('/studentlogin', function () use ($app) { verifyRequiredParams(array('username', 'password')); $username = $app->request->post('username'); $password = $app->request->post('password'); $db = new DbOperation(); $response = array(); if ($db->studentLogin($username, $password)) { $student = $db->getStudent($username); $response['error'] = false; $response['id'] = $student['id']; $response['name'] = $student['name']; $response['username'] = $student['username']; $response['apikey'] = $student['api_key']; } else { $response['error'] = true; $response['message'] = "Invalid username or password"; } echoResponse(200, $response); }); /* * * URL: http://localhost/StudentApp/v1/createfaculty * Parameters: name, username, password, subject * Method: POST * */ $app->post('/createfaculty', function () use ($app) { verifyRequiredParams(array('name', 'username', 'password', 'subject')); $name = $app->request->post('name'); $username = $app->request->post('username'); $password = $app->request->post('password'); $subject = $app->request->post('subject'); $db = new DbOperation(); $response = array(); $res = $db->createFaculty($name, $username, $password, $subject); if ($res == 0) { $response["error"] = false; $response["message"] = "You are successfully registered"; echoResponse(201, $response); } else if ($res == 1) { $response["error"] = true; $response["message"] = "Oops! An error occurred while registereing"; echoResponse(200, $response); } else if ($res == 2) { $response["error"] = true; $response["message"] = "Sorry, this faculty already existed"; echoResponse(200, $response); } }); /* * * URL: http://localhost/StudentApp/v1/facultylogin * Parameters: username, password * Method: POST * */ $app->post('/facultylogin', function() use ($app){ verifyRequiredParams(array('username','password')); $username = $app->request->post('username'); $password = $app->request->post('password'); $db = new DbOperation(); $response = array(); if($db->facultyLogin($username,$password)){ $faculty = $db->getFaculty($username); $response['error'] = false; $response['id'] = $faculty['id']; $response['name'] = $faculty['name']; $response['username'] = $faculty['username']; $response['subject'] = $faculty['subject']; $response['apikey'] = $faculty['api_key']; }else{ $response['error'] = true; $response['message'] = "Invalid username or password"; } echoResponse(200,$response); }); /* * * URL: http://localhost/StudentApp/v1/createassignment * Parameters: name, details, facultyid, studentid * Method: POST * */ $app->post('/createassignment',function() use ($app){ verifyRequiredParams(array('name','details','facultyid','studentid')); $name = $app->request->post('name'); $details = $app->request->post('details'); $facultyid = $app->request->post('facultyid'); $studentid = $app->request->post('studentid'); $db = new DbOperation(); $response = array(); if($db->createAssignment($name,$details,$facultyid,$studentid)){ $response['error'] = false; $response['message'] = "Assignment created successfully"; }else{ $response['error'] = true; $response['message'] = "Could not create assignment"; } echoResponse(200,$response); }); /* * * URL: http://localhost/StudentApp/v1/assignments/<student_id> * Parameters: none * Authorization: Put API Key in Request Header * Method: GET * */ $app->get('/assignments/:id', 'authenticateStudent', function($student_id) use ($app){ $db = new DbOperation(); $result = $db->getAssignments($student_id); $response = array(); $response['error'] = false; $response['assignments'] = array(); while($row = $result->fetch_assoc()){ $temp = array(); $temp['id']=$row['id']; $temp['name'] = $row['name']; $temp['details'] = $row['details']; $temp['completed'] = $row['completed']; $temp['faculty']= $db->getFacultyName($row['faculties_id']); array_push($response['assignments'],$temp); } echoResponse(200,$response); }); /* * * URL: http://localhost/StudentApp/v1/submitassignment/<assignment_id> * Parameters: none * Authorization: Put API Key in Request Header * Method: PUT * */ $app->put('/submitassignment/:id', 'authenticateFaculty', function($assignment_id) use ($app){ $db = new DbOperation(); $result = $db->updateAssignment($assignment_id); $response = array(); if($result){ $response['error'] = false; $response['message'] = "Assignment submitted successfully"; }else{ $response['error'] = true; $response['message'] = "Could not submit assignment"; } echoResponse(200,$response); }); /* * * URL: http://localhost/StudentApp/v1/students * Parameters: none * Authorization: Put API Key in Request Header * Method: GET * */ $app->get('/students', 'authenticateFaculty', function() use ($app){ $db = new DbOperation(); $result = $db->getAllStudents(); $response = array(); $response['error'] = false; $response['students'] = array(); while($row = $result->fetch_assoc()){ $temp = array(); $temp['id'] = $row['id']; $temp['name'] = $row['name']; $temp['username'] = $row['username']; array_push($response['students'],$temp); } echoResponse(200,$response); }); function echoResponse($status_code, $response) { $app = \Slim\Slim::getInstance(); $app->status($status_code); $app->contentType('application/json'); echo json_encode($response); } function verifyRequiredParams($required_fields) { $error = false; $error_fields = ""; $request_params = $_REQUEST; if ($_SERVER['REQUEST_METHOD'] == 'PUT') { $app = \Slim\Slim::getInstance(); parse_str($app->request()->getBody(), $request_params); } foreach ($required_fields as $field) { if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) { $error = true; $error_fields .= $field . ', '; } } if ($error) { $response = array(); $app = \Slim\Slim::getInstance(); $response["error"] = true; $response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty'; echoResponse(400, $response); $app->stop(); } } function authenticateStudent(\Slim\Route $route) { $headers = apache_request_headers(); $response = array(); $app = \Slim\Slim::getInstance(); if (isset($headers['Authorization'])) { $db = new DbOperation(); $api_key = $headers['Authorization']; if (!$db->isValidStudent($api_key)) { $response["error"] = true; $response["message"] = "Access Denied. Invalid Api key"; echoResponse(401, $response); $app->stop(); } } else { $response["error"] = true; $response["message"] = "Api key is misssing"; echoResponse(400, $response); $app->stop(); } } function authenticateFaculty(\Slim\Route $route) { $headers = apache_request_headers(); $response = array(); $app = \Slim\Slim::getInstance(); if (isset($headers['Authorization'])) { $db = new DbOperation(); $api_key = $headers['Authorization']; if (!$db->isValidFaculty($api_key)) { $response["error"] = true; $response["message"] = "Access Denied. Invalid Api key"; echoResponse(401, $response); $app->stop(); } } else { $response["error"] = true; $response["message"] = "Api key is misssing"; echoResponse(400, $response); $app->stop(); } } $app->run(); |
Now thats it, You can try testing your API.
PHP Rest API Framework SLIM Tutorial Source Code and Configuration
If you are still facing trouble in this PHP Rest API Framework Tutorial, then don’t worry here I am giving you the complete source code. And in the video you can see how you can download and configure the source code to your system. First download the source code from the link given below. And then watch the video.
[sociallocker id=1372] Restful API PHP Download [/sociallocker]
So thats all for this PHP Rest API Framework SLIM tutorial guys. In the next part we will create an Android Application using this API. If you like my posts then please share the post among your circles. Thank You 🙂