Monday, June 1, 2015

MV101 Create Web API For Online Registration


.
MV101 Create Web API For Online Registration
MyVolunteers Demo Apps
Designer’s Impression
The objective of this project is to develop online registration services submitted through mobile apps.
We need to set up a website that provides services through API. We will use the following tools:
  • Slim and NotORM Framework for this purpose.
  • Adminer script to manage the database.
  • Chrome Postman Rest Client Extension.
Then, we need to develop mobile apps that can send data to this website. We will use three different approaches of sending data from mobile apps to the server; HttpClient, HttpUrlConnection and Volley Libraries.
The demo project was developed using ADT v.21 (download here if you would like to use it) but it is compatible with Android Studio as well.

1) Download Framework Files

1.1) Index Script File

We are using Slim Framework to process the URL according to REST format.
In this script file we use the keyword “volunteers” for both GET and POST method.
We include an optional REST parameter volunteerid. If the user does not send a volunteerid value then it will be initialised with the value 0.
<?php
require 'Slim/Slim.php';
require 'NotORM.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->container->singleton('db', function () {
        include 'data_conn.php';
    return new NotORM($connection);
});
//api-user
$app->get('/volunteers(/:volunteerid)','getVolunteers');
$app->post('/volunteers(/:volunteerid)','setVolunteers');
$app->run();
function getVolunteers($volunteerid=0) {
        echo "getVolunteers ".$volunteerid;
}
function setVolunteers($volunteerid=0) {
        echo "setVolunteers ".$volunteerid;
}
?>

1.2) GET Test

We will use GET volunteers without parameter for getting all volunteers.
We will use GET volunteers with parameter for getting a specific volunteer.
will get
getVolunteers 0
will get
getVolunteers 1

1.3) POST Test

We will use POST volunteers without parameter for inserting a new volunteer.
We will use POST volunteers with parameter for updating a specific volunteer.
will get
setVolunteers 0
 
will get
setVolunteers 1

2) Database Set Up

We will use SQLite database during development.
Create the database in a separate location (ie {project root}/data/mydb.sqlite).
Create the table tblperson in this database.

2.1) Browse the adminer script file.

2.2) Create new database.

2.3) Type database name

Type exactly mydb.sdb

2.4) Create Table (through SQL command)

2.5) Run SQL

The SQL Command below will create a table with typical fields.
We may not be using all of them.
DROP TABLE IF EXISTS "tblperson";
CREATE TABLE "tblperson" (
 "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
 "name" text NULL,
 "regid" text NULL,
 "password" text NULL,
 "email" text NOT NULL,
 "photo" text NULL
);

2.6) Enter dummy data

The above details will be translated into the following SQL Commands:
INSERT INTO "tblperson" ( "name", "regid", "password", "email", "photo")
VALUES ('Albert','900625105523','pass1234','albert@gmail.com',NULL);

Enter dummy data through SQL Command
INSERT INTO "tblperson" ( "name", "regid", "password", "email", "photo")
VALUES ('John','800625105523','pass1234',        'john@gmail.com',NULL);
INSERT INTO "tblperson" ( "name", "regid", "password", "email", "photo")
VALUES ('Tony','700625105523','pass1234',        'tony@gmail.com',NULL);
INSERT INTO "tblperson" ( "name", "regid", "password", "email", "photo")
VALUES ('Sally','700625105524','pass1234','sally@gmail.com',NULL);

3) Edit Script File

3.1) Get Method

<?php
require 'Slim/Slim.php';
require 'NotORM.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->container->singleton('db', function () {
        include 'data_conn.php';
    return new NotORM($connection);
});
//api-user
$app->get('/volunteers(/:volunteerid)','getVolunteers');
$app->post('/volunteers(/:volunteerid)','setVolunteers');
$app->run();
function getVolunteers($volunteerid="") {
        // echo "getVolunteers ".$volunteerid;
        //create app instance object
        $app = \Slim\Slim::getInstance();
        //create db object from apps instance object
        $db1=$app->db;
        //create variables for returning values
        $response=array();
        $action="none";
        $actionstatus="none";
        $result=array();
        //getting data
        if ($volunteerid!=""){
                $action="selectone";
                //result as field arrays
                $tblperson = $db1->tblperson("email= ?", $volunteerid)->fetch();
                if (!empty($tblperson)){
                        $result[]=array(
                                "id"=> $tblperson["id"],
                                "name"=> $tblperson["name"],                                
                                "email"=> $tblperson["email"]
                                );
                }
                $actionstatus="done";                                
        }
        else{
                $action="selectall";
                //result as row arrays
                $tblperson = $db1->tblperson();
                if (!empty($tblperson)){
                         foreach ($tblperson as $item) {
                    $result[]  = array(
                            "id" => $item["id"],
                       "name" => $item["name"],
                       "email" => $item["email"]
                    );
                }
        }
                $actionstatus="done";                                                
        }
        //create app response
    $response = $app->response;
    //set response sontent type as json
    $response['Content-Type'] = 'application/json';
    //set response body
    //use json_encode to format the output
    $response->body( json_encode([
        'action' => $action,
        'actionstatus' => $actionstatus,
        'result' =>$result
    ]));        
}
function setVolunteers($volunteerid=0) {
        echo "setVolunteers ".$volunteerid;
}
?>
GET REST Call with REST PARAM will result with select one action.
GET REST Call without REST PARAM will result with select all action.

3.2) Post Method

<?php
require 'Slim/Slim.php';
require 'NotORM.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->container->singleton('db', function () {
        include 'data_conn.php';
    return new NotORM($connection);
});
//api-user
$app->get('/volunteers(/:volunteerid)','getVolunteers');
$app->post('/volunteers(/:volunteerid)','setVolunteers');
$app->run();
function getVolunteers($volunteerid="") {
        // echo "getVolunteers ".$volunteerid;
        //create app instance object
        $app = \Slim\Slim::getInstance();
        //create db object from apps instance object
        $db1=$app->db;
        //create variables for returning values
        $response=array();
                $action="none";
                $actionstatus="none";
                $result=array();
        //getting data
        if ($volunteerid!=""){
                $action="selectone";
                //fetch as field arrays
                $tblperson = $db1->tblperson("email= ?", $volunteerid)->fetch();
                if (!empty($tblperson)){
                        $result[]=array(
                                "id"=> $tblperson["id"],
                                "name"=> $tblperson["name"],                                
                                "email"=> $tblperson["email"]
                                );
                }
                $actionstatus="done";                                
        }
        else{
                $action="selectall";
                //fetch row arrays
                $tblperson = $db1->tblperson();
                if (!empty($tblperson)){
                         foreach ($tblperson as $item) {
                    $result[]  = array(
                            "id" => $item["id"],
                       "name" => $item["name"],
                       "email" => $item["email"]
                    );
                }
        }
                $actionstatus="done";                                                
        }
        //create app response
    $response = $app->response;
    //set response sontent type as json
    $response['Content-Type'] = 'application/json';
    //set response body
    //use json_encode to format the output
    $response->body( json_encode([
        'action' => $action,
        'actionstatus' => $actionstatus,
        'result' =>$result
    ]));        
}
function setVolunteers($volunteerid=0) {
        //echo "setVolunteers ".$volunteerid;
        //create app instance object
        $app = \Slim\Slim::getInstance();
        //create db object from apps instance object
        $db1=$app->db;
        //create variables for returning values
        $response=array();
                $action="none";
                $actionstatus="none";
                $result=array();        
        //create variables to store form param values
        $name = $app->request->post('name');
        $email = $app->request->post('email');
        //setting data
        if ($volunteerid!=""){        //update
                $action="update";        
                //if variables are not empty
                //then assign variable values to data array
                if (!(empty($name)) && !(empty($email))  &&  ($email==$volunteerid))  {
                        //echo 'valid param';
                        //find matching useremail to param email
                        $registeredperson = $db1->tblperson("email = ?", $email)->fetch();
                        //echo $registereduser;
                        //if matched(registered) then update record
                        //else update failed
                        if (!empty($registeredperson)) {//registered person
                                $action="update";
                            $data = array(
                                        "name" => $name
                            );
                            $result = $registeredperson->update($data);
                            $actionstatus="success";
                    }else{
                            $result="person not found";
                            $actionstatus="failed";
                    }
                }else{
                            $result="field errors";
                            $actionstatus="failed";
                        }                        
                }
         
        else{        //insert
                $action="insert";
                //if variables are not empty
                //then assign variable values to data array
                if (!(empty($name)) && !(empty($email)))  {
                        //echo 'valid param';
                        //find matching useremail to param email
                        $registeredperson = $db1->tblperson("email = ?", $email)->fetch();
                        //echo $registereduser;
                        //if not matched(not registered yet) then insert record
                        //else insert failed
                        if (empty($registeredperson)) {//registered person
                                $newperson = $db1->tblperson();
                                $action="insert";
                                $data = array(
                                    "name" => $name,
                                    "email" => $email
                                );
                                $result = $newperson->insert($data);        
                            $actionstatus="success";
                        }else{
                                $result = "email has been used";        
                            $actionstatus="failed";                                
                        }
                }else{
                            $result="field errors";
                            $actionstatus="failed";
                        }        
        }
        //create app response
    $response = $app->response;
    //set response sontent type as json
    $response['Content-Type'] = 'application/json';
    //set response body
    //use json_encode to format the output
    $response->body( json_encode([
        'action' => $action,
        'actionstatus' => $actionstatus,
        'result' =>strval($result)
    ]));        
}
?>
REST call without REST PARAM and empty Form Fields will result with failed status and result message field errors.
REST call without REST PARAM and filled Form Fields and registered email will result with failed status and result message  email has been used.
REST call without REST PARAM and filled Form Fields and unregistered email will result with success status and result message  new id.
REST call with REST PARAM and filled Form Fields and unmatched email will result with failed status and result message  field errors.
(unmatched means the REST PARAM value != email value)
REST call with REST PARAM and filled Form Fields and matched email will result with success status and result message  number of records affected.
(matched means the REST PARAM value = email value)
REST call with REST PARAM and filled Form Fields and matched but unregistered email will result with failed status and result message  person not found.
(matched means the REST PARAM value = email value)

DOWNLOAD



.

No comments:

Post a Comment