X
    Categories: API Tutorials and Use CasesLearn PHP Tutorials, Tips And Guides

How to Create a REST API in Codeigniter with Basic Authentication

Codeigniter is a well known framework for PHP application development. However, in the cases where the application needs to communicate across platforms, you do need a RESTful API. In almost all cases, REST API is an essential component of web apps.

What is REST API

REST stands for Representational State Transfer.  A REST API is a web service which uses HTTP methods likes GET, PUT, POST, DELETE for data manipulation over the cross platforms.

In this tutorial, I will demonstrate How you can create a REST API in Codeigniter. To create the API, I will use codeigniter-restserver, written by Phil Sturgeon and currently supported by Chris Kacerguis. I will also use the codeigniter-restclient library.

The process of creating REST API in Codeigniter covers the following steps:

  • Installation of Codeigniter framework on Cloudways
  • Database and table(s) creation
  • Setup libraries and permissions
  • Setup authentication and API key(s)
  • Setup HTTP calls (GET, PUT, POST, DELETE)
  • Test the HTTP calls.

Installation of Codeigniter on Cloudways

First sign up at Cloudways for a free account. Once the account is ready, login to your account and create a new server. Fill in the server and the application detail and select PHP Stack as your application. Next, enter application, server and project’s name.

Note: You can host unlimited applications on a single server.

Choose your provider (Google, Amazon, Vultr, DigitalOcean, Kyup), select server size according to your needs and click the Launch button. Check out the following GIF for more details:

Now that your server and application is ready, open your server by clicking the server name.

Login with the username and password provided in the Master Credentials area.

Now that you are connected to your server, go to the SSH terminal and type the following commands to install Codeigniter.

cd applications

cd applicationname/public_html

wget https://github.com/bcit-ci/CodeIgniter/archive/develop.zip

Once the download of the zip file finishes, unzip the file by using the following commands.

unzip develop.zip
mv CodeIgniter-develop codeigniter
rm index.php
rm develop.zip

At this point, the installation is complete.

Go to the Application tab on the Cloudways panel and select your application. Click the highlighted button (see the following image) to access the application. Remember to add /codeigniter to the URL and hit the Enter key.

Create Database and Table(s)

I will now create a simple database with a table named User. In order to create the database, go to the Application Management tab and launch the database manager.

Type in the following command in the SQL command field:

CREATE TABLE `tbl_user` (
 `user_id` int(11) NOT NULL,
 `user_name` varchar(40) NOT NULL,
 `user_password` varchar(40) NOT NULL,
 `user_type` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


Setting up Libraries and Permissions

First of all, download codeigniter-restserver and codeigniter-restclient libraries. Extract the contents and then drag and drop application/libraries/Format.php and application/libraries/REST_Controller.php files into the application’s directories.Remember to add require_once it at the top of the controllers in order to load them into the scope. Additionally, copy rest.php file from application/config in application’s configuration directory.

You might be interested in: How To Pass Data From Controller To View In CodeIgniter

Now create a file in the application’s root folder and name it .htaccess. Paste the following code in it.

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php/$1 [L]

Setup Authentication and API Key

To setup authentication, first create the following tables in the database:

 

CREATE TABLE `keys` (

 `id` int(11) NOT NULL,

 `key` varchar(40) NOT NULL,

 `level` int(2) NOT NULL,

 `ignore_limits` tinyint(1) NOT NULL DEFAULT '0',

 `is_private_key` tinyint(1) NOT NULL DEFAULT '0',

 `ip_addresses` text,

 `date_created` int(11) NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

CREATE TABLE `logs` (

 `id` int(11) NOT NULL,

 `uri` varchar(255) NOT NULL,

 `method` varchar(6) NOT NULL,

 `params` text,

 `api_key` varchar(40) NOT NULL,

 `ip_address` varchar(45) NOT NULL,

 `time` int(11) NOT NULL,

 `rtime` float DEFAULT NULL,

 `authorized` varchar(1) NOT NULL,

 `response_code` smallint(3) DEFAULT '0'

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

The table Keys will be used for storing the API key, and the Logs table will hold the logs of the request(s) received by the server.

Now open up application / database.php and type in your hostname, dbname and password (available in the Application Access details).

The next step is the setup of authentication. For this, open up application / autoload.php and change this line of code

$autoload['libraries'] = array( );

To this

$autoload['libraries'] = array('database');

Now go to application / rest.php and set the following entities as shown

$config['rest_enable_keys'] = TRUE;
$config['rest_logs_table'] = 'logs';
$config['rest_auth'] = 'basic';
$config['auth_source'] = '';


The authentication is now ready. Nest up is the creation of the model and HTTP calls.

Setup HTTP Calls

I will now create two files.

Go to application/controllers and create a new file with the name of api.php. Paste the following code in it.

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

require(APPPATH.'/libraries/REST_Controller.php');
class Api extends REST_Controller
{

       public function __construct() {
               parent::__construct();
               $this->load->model('user_model');

       }    
       public function user_get(){
           $r = $this->user_model->read();
           $this->response($r); 
       }
       public function user_put(){
           $id = $this->uri->segment(3);

           $data = array('name' => $this->input->get('name'),
           'pass' => $this->input->get('pass'),
           'type' => $this->input->get('type')
           );

            $r = $this->user_model->update($id,$data);
               $this->response($r); 
       }

       public function user_post(){
           $data = array('name' => $this->input->post('name'),
           'pass' => $this->input->post('pass'),
           'type' => $this->input->post('type')
           );
           $r = $this->user_model->insert($data);
           $this->response($r); 
       }
       public function user_delete(){
           $id = $this->uri->segment(3);
           $r = $this->user_model->delete($id);
           $this->response($r); 
       }
    

}


Next, go to application/models and paste the following code in it.

<?php

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



/**

*

*/

class User_model extends CI_Model

{

public function read(){

   

       $query = $this->db->query("select * from `tbl_user`");

       return $query->result_array();

   }



   public function insert($data){

       

       $this->user_name    = $data['name']; // please read the below note

       $this->user_password  = $data['pass'];

       $this->user_type = $data['type'];



       if($this->db->insert('tbl_user',$this))

       {    

           return 'Data is inserted successfully';

       }

         else

       {

           return "Error has occured";

       }

   }



   public function update($id,$data){

   

      $this->user_name    = $data['name']; // please read the below note

       $this->user_password  = $data['pass'];

       $this->user_type = $data['type'];

       $result = $this->db->update('tbl_user',$this,array('user_id' => $id));

       if($result)

       {

           return "Data is updated successfully";

       }

       else

       {

           return "Error has occurred";

       }

   }



   public function delete($id){

   

       $result = $this->db->query("delete from `tbl_user` where user_id = $id");

       if($result)

       {

           return "Data is deleted successfully";

       }

       else

       {

           return "Error has occurred";

       }

   }



}

 

Testing the HTTP Calls

To test the HTTP calls of the API, I will use Postman.Go to the Postman, Set the method to GET , then set the authentication and API key as shown below:

Now to test the POST request, set the request to POST and add the authentication and API key. Fill in the variables as shown below:

Next, I will test the PUT request. Pass the id in the 3rd segment of the URL, set the request to PUT, set the authentication and the API key and fill in the parameters as shown below:

To test the DELETE request, pass the id in the 3rd segment of the URL, set the request to DELETE, set the authentication and the API key and fill in the parameters as shown below:

To Sum Up

In this tutorial. I described how you could setup authentication for a REST API in Codeigniter. I created four API calls for data manipulation.

If you need any help with the code or the idea of implementing your own RESTful API in Codeigniter, do leave a comment below.

Saquib Rizwan: Saquib is a PHP Community Expert at Cloudways - A Managed PHP Hosting Cloud Platform. He is well versed in PHP and regularly contributes to open source projects. For fun, he enjoys gaming, movies and hanging out with friends. You can email him at saquib.rizwan@cloudways.com