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 += "

  • Please enter Email

“;
}
if(password == “”){
$(“#password”).addClass(“error”);
error += ”

  • Please enter Password

“;
}
if(error != “”){
$(“.error-div ul”).html(error);
return;
}else{
API.call(“/login”, function(data){
if(data.error == 0){
error += ”

  • "+data.message+"

“;
$(“.error-div ul”).html(error);
}else{
error += ”

  • "+data.message+"


";
$(".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.

8 Comments

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

    1. 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);
      }

Leave a Reply

Your email address will not be published. Required fields are marked *