Create a RESTful API using PHP, My-sql and Slim-Framework

January 1, 2015
by Inaam Hussain

In this tutorial we will learn to create RESTful API using PHP, My-sql and Slim-Framework.
I have create a sample login application to demonstrate the working.

Here is my folder structure below.

Folder_structure_API

API Folder Structure

View demohere
Download Codehere

Steps to create APIs :

First download the code from the above link.You will need a server and phpmyadmin to run the code, alternatively you can also run the program on a local server using xampp or wamp.

For creating an API of your own, all you have to do is change the following files as required,rest other stuff has been pre-configured by me so no need to worry about it for basic implementation.You can download code from here.

  1. api/includes/db_config.php” : Add database connection connection.
  2. api/routes/site.php” : Here you should define the url for the API and add processing code and output your required json response. Refer Create login api section below for an example.

Database Configuration :

Create sample table “users“. or you can also use “apidb.sql” file.

CREATE TABLE IF NOT EXISTS `users` (
  `id` INT(255) NOT NULL AUTO_INCREMENT,
  `FirstName` VARCHAR(255) NOT NULL,
  `LastName` VARCHAR(255) NOT NULL,
  `EmailAddress` VARCHAR(255) NOT NULL,
  `Password` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

and do the necessary database connectivity changes in “db_config.php” file.

api/includes/db_config.php
global $conn;
$conn = new mysqli("localhost", "root", "", "apidb"); /*mysqli("{{server}}", "{{username}}", "{{pwd}}", "{{database name}}")*/

Create Login API :

We have already seen the DB connection above, now we will do the url routing for login API.

api/routes/site.php
$app->get('/login',function() use($app) {
    $req = $app->request();
    $requiredfields = array(
        'email',
        'password'
    );
    // validate required fields
    if(!RequiredFields($req->get(), $requiredfields)){
        return false;
    }
    $email = $req->get("email");
    $password = $req->get("password");
    global $conn;
    $sql='SELECT * from users where EmailAddress="'.$email.'" and Password="'.$password.'"';
    $rs=$conn->query($sql);
    $arr = $rs->fetch_array(MYSQLI_ASSOC);
    if($arr == null){
        echo json_encode(array(
            "error" => 1,
            "message" => "Email-id or Password doesn't exist",
        ));
        return;
    }
    echo json_encode(array(
        "error" => 0,
        "message" => "User logged in successfully",
        "users" => $arr
    ));
});
  •  $app->get(‘/login‘,function() use($app)) :- Define route url. so calling this url from front-end will get appropriate response. ( ex : {{domain}}/api/login).
  • $req = $app->request() :- Request for data which is coming from font-end.
  • $requiredfields = array( ‘email‘ , ‘password‘) :- Array for holding list of mandatory fields which will later be validated.
  • RequiredFields($req->get(), $requiredfields) function takes in two parameters the data and an array of mandatory fields, this function will validate if the required fields are present in the request.Check functions.php for the code.
  •  if(!RequiredFields($req->get(), $requiredfields)){ return false; } :- Check if it is false then return json with error 1 and message missing data.
  • Then we do mysql query to check whether user is registered or not. based on that will will set appropriate json data.
  • Now API is ready to run.

Call Login API from front-end :

We have created Login API above, now will call that API from from our front-end and will get response based on validation.

First will see how to handle ajax call for all API.

js/apicall.js
var API = {
    call:function(url,callback,data){
        var data = (!!data) ? data : {};
        var callback = (!!callback) ? callback : function(){};
        $.ajax({
            dataType: "jsonp",
            crossDomain: true,
            xhrFields: { withCredentials: true },
            url: "api/"+url,
            data:data,
            success:callback,
            error:function(data){
                console.log(data);
            }
        });
    }
}

We have created a call function in API object in which we are passing three parameters (url callback , data).

  •  url : url which we created for login API ( i.e : “/login”).
  • callback : on success after calling api which function should work that we can pass to callback.
  • data : in data we can pass object data to get response based on that.

Now, lets see how login API call and other functionality works.

js/main.js
$(document).ready(function(){
    $('body').keypress(function (e) {
        var key = e.which;
        if(key == 13) // the enter key code
        {
            $('#login-btn').click();
            return false;
        }
    });
    $(document).on("click","#login-btn", function(){
        $("#email, #password").removeClass("error");
        $(".error-div ul").html("");
        var error = "";
        var email = $("#email").val();
        var password = $("#password").val();
        if(email == ""){
            $("#email").addClass("error");
            error += "<li>Please enter Email</li>";
        }
        if(password == ""){
            $("#password").addClass("error");
            error += "<li>Please enter Password</li>";
        }
        if(error != ""){
            $(".error-div ul").html(error);
            return;
            }else{
            API.call("/login", function(data){
                if(data.error == 0){
                    error += "<li>"+data.message+"</li>";
                    $(".error-div ul").html(error);
                }else{
                    error += "<li>"+data.message+"</li>";
                    $(".error-div ul").html(error);
                }
            },{email:email,password:password});
        }
    });
});

Before calling API checking that data is not null.

If it’s not null then call the API (e.x : API.call(“/login”, callback, {email : “[email protected]”}),we should get appropriate response based on the input data and validations from the server script.

See demo for quick overview.

I hope this tutorial will help you for Create API easily in future.

About

Engineer. Blogger. I like to be updated on new upcoming emerging technologies.

Free PDF

Subscribe and get AngularJS Tips PDF. We never spam!
First Name:
Email:

9 comments

  1. Massimo
    |

    if(data.error == 0){
    error += “”+data.message+””;
    $(“.error-div ul”).html(error);
    }else{
    error += “”+data.message+””;
    $(“.error-div ul”).html(error);
    }
    In both conditions error is set with the same value…

    • |

      No only in else condition will set the error.
      Actually in if condition i have to name it as a message instead of error .
      in both if and else condition message data will come from api (i.e: For Error :- “Email-id or Password doesn’t exist” & For Message :- “User logged in successfully”).
      Like,
      var message;
      if(data.error == 0){
      message += “”+data.message+””;
      $(“.error-div ul”).html(message);
      }else{
      error += “”+data.message+””;
      $(“.error-div ul”).html(error);
      }

  2. Joel
    |

    From security point of view it’s a very bad idea to transfer the password with GET statement.

    • |

      Yes. you are correct joel. its should be post request only. will update that soon.
      Thanks.

  3. mindy
    |

    how to redirect page when enter corect email id and password?

    • |

      HI Mindy,
      Once user login successfully then we need to use location.href to send to another page.
      Thanks

  4. Daniel Ruiz
    |

    HI! Once I’ve been logged in, how do you make next request (logged functions) to this api?

    • |

      In callback of that request, you will get whether user credentials is correct or not. and based on that you will call next request.
      Thanks.

  5. |

    It’s going to be finish off mine day, except before end I am reading this enormous piece of
    writing to increase my experience.

Leave a Comment