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.
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 🙂

Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.
Hi.
You have most of your articles with hosting done on hostinger.in and I tried implementing this one on hostinger. But there is one error I have encountered several times. I can’t access the MySql database. I implemented my own custom code and I always get the error in registering a user. So I narrow down the possibilities of where the error could have occurred and it seems I can’t access the DB. The credentials are correct and when I wasn’t implementing REST architecture, it was working. I had encountered the same error a month ago when I tried REST api myself.
The code can be found here:
http://stackoverflow.com/questions/36542641/rest-api-structure-prevents-database-access
Thanks!
Hi Basu, I´m Marcelo I was reading your post and I think you have the same problems that i had with hostinger.
I have 2 hosting, one at hostinger ( free ) and other, in other server ( paid ).
Problem with hostinger ( free ) is that hostinger not allow to access to your database in remote mode.
in my payment plan, I had to request that enables me the remote access to the database.
My Email is mpickelny@yahoo.com
If you want to send me an email and we try to develop and share solutions. I have to develop the same project.
Marcelo
Amazing artikel, but why not use NoTORM library..>?
Hi Belal.
I am using Hostinger and PHO 5.6
The instruction rquire :
require_once ‘include/DbOperation.php’;
require ‘libs/Slim/Slim.php’;
Send me back this error:
Warning: require_once(include/DbOperation.php): failed to open stream: No such file or directory in /home/u466913894/public_html/AppGestionRest/v1/index.php on line 5
Fatal error: require_once(): Failed opening required ‘include/DbOperation.php’ (include_path=’.:/opt/php-5.6/pear’) in /home/u466913894/public_html/AppGestionRest/v1/index.php on line 5
May I have your comments and help. Is there any relationship with the PHO version or ini.php file?
Thanks in advance for your help.
Óscar
Hi. Belal, please don´t forget part #3 of this tutorial.
we are waiting for it.
thanks
Marcelo
It will be live soon.. I have almost completed it..
Please let me no if you have it…Part3
Please publish the part 3 of your video.
Hi..Belal.. when do you think part 3 will be available..
Thanks !!!
How to download the source code
hi Belal,
It was amazing tutorials. Glad to read your article.
I have one question for you. Why the PUT not working in function verifyRequiredParams ?
Thank you.
I have the same problem, only “PUT” method not working
I have sovled the problem, in the api client tool and change the status “form-data” to “x-www-form-urlencoded”, and PUT method is working
Please don’t forget part #3
Thanks
Hello Belal, your tutorials seems so very simple enough to understand, a great approach for us as a beginner in android programming, you really help us much understand the basic concept of how REST web service works. One last thing, you have said above that we can download the source code, but i can’t see any dowloand links in this page. Can i ask you a favor to have some copy of full source code of this Rest API Framework tutorial, coz i wanna spend some time working on it this weekend. Well, i am a nerd girl that wanna try programming this summer. Im hoping for your sweet reply, if you’ve got some nerves to give me a copy, you can send it to my email, hotmarycorleone@gmail.com. Thank you so much in advance. kisses from Italy and America.
hello guys, im currently working on this rest api project, and im having some issues on accessing all assignments created using faculty accounts, an error message says “Api key is missing”.
I am using PostMan Rest Client.
An error returns when i access this url : http://localhost/StudentApp/v1/assignments/1
where 1, is the student id generated by students table in database;
using GET method like what you’ve mentioned above.
My question is, json returns an error of lack of supplied API key, to where the hell i should put the api key. Your tutorial doesn’t show any parameter name and value for that. Im sorry but im just kind of newbie here, so im a little bit impatience. love, marycorleone
Hiii Belal, even i am also having the same problem of (API key is missing)
An error returns on this url : http://localhost/StudentApp/v1/assignments/1
url : http://localhost/StudentApp/v1/students
{
“error”: true,
“message”: “Api key is misssing”
}
You need to put the api key in http headers.. use a rest client and put the api key in headers
Sorry Belal Bro But am not getting you, can you please make it more easy for me bcoz i am working first time on REST API and that too through http://www.simplifiedcoding.net
Thankyou brother for lovely script…
Also waiting for you next project that is Part 3 in Android 🙂
Hey belal can u please specify the parameter for apikey and thanks for the tutorial …..
Hi please don’t forget part number 3.
I need to finish a project.thanks
What is the benefit of Api key in header?
Please don’t forget part #3
I had some probelmas with the connection to my database , however I worked correctly as follows ( ” EXTREMELY UNSAFE ” )
Api works perfectly just that I failed on connection to my database
I had some probelmas with the connection to my database , however I worked correctly as follows ( ” EXTREMELY UNSAFE ” )
$stmt = $this->con->prepare(“INSERT INTO faculties(name, username, password, subject, api_key) values(‘”.$name.”‘, ‘”.$username.”‘, ‘”.$password.”‘, ‘”.$subject.”‘, ‘”.$apikey.”‘)”);
REMOVE THIS LINE //$stmt->bind_param(“sssss”, $name, $username, $password, $subject, $apikey);
OR WIDTH PDO MAYBE
THANKS FOR THE GREAT CODE TUTORIAL!!!!!!!!!!!!!
Hello
Very great tutorial but i got a problem with queries in DbOperation.php file. I can’t insert in the database. I always have “message”: “Oops! An error occurred while registereing” response in my rest client. It seems that $stmt->bind_param(“ssss”, $name, $username, $password, $apikey) line is not working. Do you have an issue for that please???
hey i have the same error , do you have any idea
Hi Friends,
I was facing the issue, after googling I found the solution. Issue was in passing parameters, I was passing parameters in querystring, Now I have solved this issue by passing parameters in (Using Postman ciient) “Body”->”x-www-form-urlencoded” here you can see “Key” and “Value” just pass your parameters here. Done.
Thank you Bilal bhai.
the code is working
Hey Manich , I get always {
“error”: true,
“message”: “Oops! An error occurred while registereing” when I try the create a student do you have any idea the solve the probleme,,, thank you
thanks a million Belal Khan,after enough debugging i have completed my first PHP Rest API Framework SLIM project.i have learnt a lot,nevertheless i have found implementing a REST API using the Slim Framework is more challenging as compared to implementing a REST API using node.js and express.js
Hi,
I found a small problem in code, where if post method contains large number of columns, then echoResponse() is returning empty data.
In below code I verified number of rows which is getting increase, but in response it is returning empty value.
$response[‘data’] = array();
$var = 0;
while($row = $result->fetch_assoc()){
$temp = array();
$temp[‘post_data_value’]=$row[‘post_data_value’];
array_push($response[‘data’],$temp);
$var++;
}
echo $var; // number gets increase as expected
echoResponse(200,$response);
I tried by keep lesser number of rows, but in that case everything works fine.Could you please let me know the reason.
typo : *post method contains large number of rows
Hi.. Thanks for the nice tutorial. Can you give example for raw HTTP post? I need json POST request. Json contains many object and array. Can you give a simple example for raw HTTP post?
To read raw json data you can use the following code instead of in any function where ever method is post or put
// $name = $app->request->post(‘name’);
// $username = $app->request->post(‘username’);
// $password = $app->request->post(‘password’);
$app->post(‘/createstudent’, function () use ($app) {
$request = \Slim\Slim::getInstance()->request();
$update = json_decode($request->getBody())
$name = $update[0]->name;
$username = $update[0]->username;
$password = $update[0]->password;
}
If you do not want to check passed parameter passed to any function then just comment code from any methods
//Verifying the required parameters
verifyRequiredParams(array(‘name’, ‘username’, ‘password’));
if you required to check then user the following sniped instead
function verifyRequiredParams($required_fields)
{
……
//Getting the request parameters
//$request_params = $_REQUEST;
comment out above code
$request = \Slim\Slim::getInstance()->request();
$request_params_json = json_decode($request->getBody());
$request_params = array();
foreach($request_params_json as $row)
{
foreach($row as $key => $val)
{
$request_params[$key] = $val;
}
}
}
To test API fron rest client or postman just select method post or put as you required
http://localhost/StudentApp/v1/createstudent
below select Body
and then select row option
and type json in format
[{
“name”:”student 1″,
“username”: “std2”,
“password”: “123”
}]
and finally click send button you will get in response
{
“error”: false,
“message”: “You are successfully registered”
}
Thanks …
Hi.. Thanks for the nice tutorial. I am very new PHP. I am trying to create own app for Android with help of PHP. I need to send Json to server and receive Json response from server. Now I can send a simple request (Only contains params/Form data) to the server and can get Json response. I need to send raw HTTP request. Can you give a example for raw HTTP post? I need json POST request. Json contains many object and array. Can you give a simple example for raw HTTP post?
localhost/StudentApp/v1/assignments/1
{“error”:true,”message”:”Api key is misssing”}
how can we put the API key in the headers ? and what is the api key for 2
Thank you
wow, such a splendid tutorial. Ave followed it to the end but you have left me hanging. Please send me the link to the android app bearing this student teacher Rest Api that you have just built above
I have a issue about the error about assignments:
localhost/StudentApp/v1/assignments/1
{“error”:true,”message”:”Api key is misssing”}
I put in my HEADER :
Authorization: …..API KEY…..
NOW it Work
Don’t forget Part 3.
I can’t dowload source ?
please check again
Congratulations, good work!
Can not download source code?
Could you upgrade again?
Hi,
The Dropbox link is disabled . can you share the code on github or bitbucket or mail me?
Thanks
can you share the 3rd video part of video
Very nice tutorial.
Thanks for sharing.
kindly upload part 3 ASAP
plz upload part 3
Thank you so much for the tutorial. Please upload part 3, I have to finish a project.
Hey how do retrieve student data from get method!
I’m using api_key as a parameter but it showing error true
It’s awesome!but this case how to download.
working fine in localhost but in live hosting shows a error as
{
“error”: true,
“message”: “Api key is misssing”
}
Thank you for publishing this article.
Need to update to reflect Slim3 as there are some changes in the framework.
(HY000/1049): Unknown database ‘db_studentapp’
source code does not exist any more. would you give me or reativate share link?
Will update the link very soon.
sir file not downloading from link
error file not found on drive
please share and i want to connect with sql sever 2012
Yes I accidentally deleted files from my gdrive.. I am trying to fix the links.. You will get it soon.
Thanks for the lessons!!! Unfortunately, I can’t find part 3 of the “PHP Rest API Framework SLIM for creating a REST API”. The lessons are very good.