Saturday, 10 August 2019

Codeigniter 3 - Make CRUD Rest API

Part - 1




Part - 2




Part - 3




Part - 4




Codeigniter is a Simple and Great PHP framework for web application development. There are many cases where Web based application needs communication with other application on web, then at the time we need RESTful API. If your web application has API then it can be very easily communicate with other application, because now API is an essential components of web based application.

What is REST API


We all know REST full form is Representational State Transfer. REST API is on type of Web services which has been use the HTTP different methods like POST, PUT, GET and DELETE for data exchange on the web.

Now in your mind one question arise why need to make API for our web application. If you have make API for you application, then you can easily make mobile app for your web application. Because in mobile app you need to send and received data by using API. There is one other benifits is that by making REST API web services, you can develop web and mobile application be using same database and you can access your data from both web and mobile application at the same time. So, this is the main benifits of developing API for you web application.

In this post we will share this tutorial, in which we will create restful web services in this Codeigniter 3 framework. We will make REST API in Codeigniter which will be used for perform CRUD operation like Insert, Update and Delete mysql data. Here we will not use any Codeigniter library for make CRUD RESTful API, but here we will make CRUD API from scratch. Below you can find step by step process for making CRUD API in Codeigniter.

  • Create Table
  • Make Database Connection
  • Create API Controller
  • Create API Model
  • Create Test API Controller
  • Create View File for Output







Create Table


First we need to make table in your Mysql database, for this you have to run following SQL code in your phpmyadmin. It will make tbl_sample table in your database.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_sample`
--

CREATE TABLE `tbl_sample` (
  `id` int(11) NOT NULL,
  `first_name` varchar(250) NOT NULL,
  `last_name` varchar(250) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_sample`
--
ALTER TABLE `tbl_sample`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_sample`
--
ALTER TABLE `tbl_sample`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;




Make Database Connection


Once you have creating table in your mysql database, Now you have to go to your Codeigniter working folder, and open application/config/database.php and under this you have define your mysql database configuration.


<?php

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root',
 'password' => '',
 'database' => 'testing',
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => FALSE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE
);

?>


Create API Controller


Now we need to start How to make RESTful API web services in Codeigniter framework. So first we need to make API controller for send and received API http request. This class will received HTTP request for send data in JSON format and received data by using different HTTP request. In this class, we have make following method for handle HTTP request.

__construct() - This is PHP magic function, this function will be execute when object of this class has been created and it will load API model and Codeigniter form library.

index() - This method has been received API request for fetch all data from Mysql table and return all data to HTTP request in JSON format.

insert() - This method has been used for insert or add data into Mysql table, it will received api request for insert or add data into mysql table, and send response in JSON string format.

fetch_single() - This method has been used for fetch single record from mysql table based on value of id and return data in JSON format.

update() - This method of API class has been received request for update or Edit Mysql table data.

delete() - This method has received request for Delete or remove data and it will give reponse in JSON format.

application/controllers/Api.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Api extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  $this->load->model('api_model');
  $this->load->library('form_validation');
 }

 function index()
 {
  $data = $this->api_model->fetch_all();
  echo json_encode($data->result_array());
 }
 
 function insert()
 {
  $this->form_validation->set_rules("first_name", "First Name", "required");
  $this->form_validation->set_rules("last_name", "Last Name", "required");
  $array = array();
  if($this->form_validation->run())
  {
   $data = array(
    'first_name' => trim($this->input->post('first_name')),
    'last_name'  => trim($this->input->post('last_name'))
   );
   $this->api_model->insert_api($data);
   $array = array(
    'success'  => true
   );
  }
  else
  {
   $array = array(
    'error'    => true,
    'first_name_error' => form_error('first_name'),
    'last_name_error' => form_error('last_name')
   );
  }
  echo json_encode($array, true);
 }

 function fetch_single()
 {
  if($this->input->post('id'))
  {
   $data = $this->api_model->fetch_single_user($this->input->post('id'));
   foreach($data as $row)
   {
    $output['first_name'] = $row["first_name"];
    $output['last_name'] = $row["last_name"];
   }
   echo json_encode($output);
  }
 }

 function update()
 {
  $this->form_validation->set_rules("first_name", "First Name", "required");
  $this->form_validation->set_rules("last_name", "Last Name", "required");
  $array = array();
  if($this->form_validation->run())
  {
   $data = array(
    'first_name' => trim($this->input->post('first_name')),
    'last_name'  => trim($this->input->post('last_name'))
   );
   $this->api_model->update_api($this->input->post('id'), $data);
   $array = array(
    'success'  => true
   );
  }
  else
  {
   $array = array(
    'error'    => true,
    'first_name_error' => form_error('first_name'),
    'last_name_error' => form_error('last_name')
   );
  }
  echo json_encode($array, true);
 }

 function delete()
 {
  if($this->input->post('id'))
  {
   if($this->api_model->delete_single_user($this->input->post('id')))
   {
    $array = array(
     'success' => true
    );
   }
   else
   {
    $array = array(
     'error' => true
    );
   }
   echo json_encode($array);
  }
 }
 
}


Create API Model


This API model class has been used for perform API request database side operation. This class has been received request from API controller for Database related query. In this class we have make following method.

fetch_all() - This method has been used for fetch all data from mysql table and send all data to API controller index() mehtod.

insert_api($data) - This is second method of API Model class, and this method will be used for insert or add data related database operation.

fetch_single_user($user_id) - This method is used for Database related operation of select single records from Mysql table.

update_api($user_id, $data) - This method of Models class has been used for Mysql Database Update or Edit operation.

delete_single_user($user_id) - This method has been used for perform Delete or Remove Database crud operation.

application/models/Api_model.php

<?php
class Api_model extends CI_Model
{
 function fetch_all()
 {
  $this->db->order_by('id', 'DESC');
  return $this->db->get('tbl_sample');
 }

 function insert_api($data)
 {
  $this->db->insert('tbl_sample', $data);
  if($this->db->affected_rows() > 0)
  {
   return true;
  }
  else
  {
   return false;
  }
 }

 function fetch_single_user($user_id)
 {
  $this->db->where("id", $user_id);
  $query = $this->db->get('tbl_sample');
  return $query->result_array();
 }
 function update_api($user_id, $data)
 {
  $this->db->where("id", $user_id);
  $this->db->update("tbl_sample", $data);
 }
 
 function delete_single_user($user_id)
 {
  $this->db->where("id", $user_id);
  $this->db->delete("tbl_sample");
  if($this->db->affected_rows() > 0)
  {
   return true;
  }
  else
  {
   return false;
  }
 }
}


Create Test API Controller


Above we have make RESTful API for perform CRUD operation. Now need to test that API, so here we have make one another controller for test our RESTful API web services. For check API working or not here we have make some method, which has send HTTP request to API controller for different operation. In this class, we have make following method.

index() - This is the root method of this controller class. This method has load api_view.php file in browser.

action() - This is another method of this Test_Api.php Class. First in this method we have define api url and then after we have use cURL library for send HTTP request to API class for send and received data.

application/controllers/Test_api.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Test_api extends CI_Controller {

 function index()
 {
  $this->load->view('api_view');
 }

 function action()
 {
  if($this->input->post('data_action'))
  {
   $data_action = $this->input->post('data_action');

   if($data_action == "Delete")
   {
    $api_url = "http://localhost/tutorial/codeigniter/api/delete";

    $form_data = array(
     'id'  => $this->input->post('user_id')
    );

    $client = curl_init($api_url);

    curl_setopt($client, CURLOPT_POST, true);

    curl_setopt($client, CURLOPT_POSTFIELDS, $form_data);

    curl_setopt($client, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($client);

    curl_close($client);

    echo $response;




   }

   if($data_action == "Edit")
   {
    $api_url = "http://localhost/tutorial/codeigniter/api/update";

    $form_data = array(
     'first_name'  => $this->input->post('first_name'),
     'last_name'   => $this->input->post('last_name'),
     'id'    => $this->input->post('user_id')
    );

    $client = curl_init($api_url);

    curl_setopt($client, CURLOPT_POST, true);

    curl_setopt($client, CURLOPT_POSTFIELDS, $form_data);

    curl_setopt($client, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($client);

    curl_close($client);

    echo $response;







   }

   if($data_action == "fetch_single")
   {
    $api_url = "http://localhost/tutorial/codeigniter/api/fetch_single";

    $form_data = array(
     'id'  => $this->input->post('user_id')
    );

    $client = curl_init($api_url);

    curl_setopt($client, CURLOPT_POST, true);

    curl_setopt($client, CURLOPT_POSTFIELDS, $form_data);

    curl_setopt($client, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($client);

    curl_close($client);

    echo $response;






   }

   if($data_action == "Insert")
   {
    $api_url = "http://localhost/tutorial/codeigniter/api/insert";
   

    $form_data = array(
     'first_name'  => $this->input->post('first_name'),
     'last_name'   => $this->input->post('last_name')
    );

    $client = curl_init($api_url);

    curl_setopt($client, CURLOPT_POST, true);

    curl_setopt($client, CURLOPT_POSTFIELDS, $form_data);

    curl_setopt($client, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($client);

    curl_close($client);

    echo $response;


   }





   if($data_action == "fetch_all")
   {
    $api_url = "http://localhost/tutorial/codeigniter/api";

    $client = curl_init($api_url);

    curl_setopt($client, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($client);

    curl_close($client);

    $result = json_decode($response);

    $output = '';

    if(count($result) > 0)
    {
     foreach($result as $row)
     {
      $output .= '
      <tr>
       <td>'.$row->first_name.'</td>
       <td>'.$row->last_name.'</td>
       <td><butto type="button" name="edit" class="btn btn-warning btn-xs edit" id="'.$row->id.'">Edit</button></td>
       <td><button type="button" name="delete" class="btn btn-danger btn-xs delete" id="'.$row->id.'">Delete</button></td>
      </tr>

      ';
     }
    }
    else
    {
     $output .= '
     <tr>
      <td colspan="4" align="center">No Data Found</td>
     </tr>
     ';
    }

    echo $output;
   }
  }
 }
 
}

?>


Create View File for Output


In Codeigniter framework, view file mainly used for display output HTML output in browser. So here also this file has been used for display API output in browser. Here we have use jQuery and Bootstrap library. Here we want to make single page application by using API in Codeigniter framework. So here we have use Bootstrap model for insert or update data. In this file we have also use Ajax request for perform CRUD operation request.

application/views/api_view.php

<html>
<head>
    <title>CURD REST API in Codeigniter</title>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    
</head>
<body>
    <div class="container">
        <br />
        <h3 align="center">Create CRUD REST API in Codeigniter - 4</h3>
        <br />
        <div class="panel panel-default">
            <div class="panel-heading">
                <div class="row">
                    <div class="col-md-6">
                        <h3 class="panel-title">CRUD REST API in Codeigniter</h3>
                    </div>
                    <div class="col-md-6" align="right">
                        <button type="button" id="add_button" class="btn btn-info btn-xs">Add</button>
                    </div>
                </div>
            </div>
            <div class="panel-body">
                <span id="success_message"></span>
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>First Name</th>
                            <th>Last Name</th>
                            <th>Edit</th>
                            <th>Delete</th>
                        </tr>
                    </thead>
                    <tbody>
                        
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>

<div id="userModal" class="modal fade">
    <div class="modal-dialog">
        <form method="post" id="user_form">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Add User</h4>
                </div>
                <div class="modal-body">
                    <label>Enter First Name</label>
                    <input type="text" name="first_name" id="first_name" class="form-control" />
                    <span id="first_name_error" class="text-danger"></span>
                    <br />
                    <label>Enter Last Name</label>
                    <input type="text" name="last_name" id="last_name" class="form-control" />
                    <span id="last_name_error" class="text-danger"></span>
                    <br />
                </div>
                <div class="modal-footer">
                    <input type="hidden" name="user_id" id="user_id" />
                    <input type="hidden" name="data_action" id="data_action" value="Insert" />
                    <input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script type="text/javascript" language="javascript" >
$(document).ready(function(){
    
    function fetch_data()
    {
        $.ajax({
            url:"<?php echo base_url(); ?>test_api/action",
            method:"POST",
            data:{data_action:'fetch_all'},
            success:function(data)
            {
                $('tbody').html(data);
            }
        });
    }

    fetch_data();

    $('#add_button').click(function(){
        $('#user_form')[0].reset();
        $('.modal-title').text("Add User");
        $('#action').val('Add');
        $('#data_action').val("Insert");
        $('#userModal').modal('show');
    });

    $(document).on('submit', '#user_form', function(event){
        event.preventDefault();
        $.ajax({
            url:"<?php echo base_url() . 'test_api/action' ?>",
            method:"POST",
            data:$(this).serialize(),
            dataType:"json",
            success:function(data)
            {
                if(data.success)
                {
                    $('#user_form')[0].reset();
                    $('#userModal').modal('hide');
                    fetch_data();
                    if($('#data_action').val() == "Insert")
                    {
                        $('#success_message').html('<div class="alert alert-success">Data Inserted</div>');
                    }
                }

                if(data.error)
                {
                    $('#first_name_error').html(data.first_name_error);
                    $('#last_name_error').html(data.last_name_error);
                }
            }
        })
    });

    $(document).on('click', '.edit', function(){
        var user_id = $(this).attr('id');
        $.ajax({
            url:"<?php echo base_url(); ?>test_api/action",
            method:"POST",
            data:{user_id:user_id, data_action:'fetch_single'},
            dataType:"json",
            success:function(data)
            {
                $('#userModal').modal('show');
                $('#first_name').val(data.first_name);
                $('#last_name').val(data.last_name);
                $('.modal-title').text('Edit User');
                $('#user_id').val(user_id);
                $('#action').val('Edit');
                $('#data_action').val('Edit');
            }
        })
    });

    $(document).on('click', '.delete', function(){
        var user_id = $(this).attr('id');
        if(confirm("Are you sure you want to delete this?"))
        {
            $.ajax({
                url:"<?php echo base_url(); ?>test_api/action",
                method:"POST",
                data:{user_id:user_id, data_action:'Delete'},
                dataType:"JSON",
                success:function(data)
                {
                    if(data.success)
                    {
                        $('#success_message').html('<div class="alert alert-success">Data Deleted</div>');
                        fetch_data();
                    }
                }
            })
        }
    });
    
});
</script>


So, this is step by step guide for build CRUD RESTful API in Codeigniter. So, if you want to learn Simple way for develop API in Codeigniter, then this post will help you.

0 comments:

Post a Comment