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

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 demo – here
Download Code – here
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 apisection 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 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 : “test@test.com”}),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.

Comments

Popular posts from this blog

DeltaPi softwares

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)