PHP Rest API Framework SLIM to Create REST API – 2

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.

URLMethodParameters
/createstudentPOSTname, username, password
/studentloginPOSTusername, password
/createfacultyPOSTname, username, password, subject
/facultyloginPOSTusername, password
/createassignmentPOSTname, details, facultyid, studentid
/assignments/:idGETstudent api key
/studentsGETfaculty api key
/submitassignment/:idPUTfaculty 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

http://localhost/StudentApp/v1/studentlogin

http://localhost/StudentApp/v1/createfaculty

http://localhost/StudentApp/v1/facultylogin

http://localhost/StudentApp/v1/createassignment

http://localhost/StudentApp/v1/assignments/2

In the above URL 2 is the student id.

http://localhost/StudentApp/v1/students

http://localhost/StudentApp/v1/submitassignment/3

Here 3 is the assignment id.

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

Updating index.php

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 🙂

57 thoughts on “PHP Rest API Framework SLIM to Create REST API – 2”

  1. 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!

    Reply
    • 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

      Reply
  2. 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

    Reply
  3. 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.

    Reply
  4. 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.

    Reply
  5. 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

    Reply
  6. 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!!!!!!!!!!!!!

    Reply
  7. 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???

    Reply
    • 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.

      Reply
    • 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

      Reply
  8. 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

    Reply
  9. 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.

    Reply
  10. 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?

    Reply
    • 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 …

      Reply
  11. 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?

    Reply
  12. 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

    Reply
  13. 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

    Reply
  14. 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

    Reply
  15. Hey how do retrieve student data from get method!

    I’m using api_key as a parameter but it showing error true

    Reply
  16. Thank you for publishing this article.
    Need to update to reflect Slim3 as there are some changes in the framework.

    Reply
  17. sir file not downloading from link
    error file not found on drive
    please share and i want to connect with sql sever 2012

    Reply
  18. 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.

    Reply

Leave a Comment