This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Join the live AMA session with Adam Silverstein on open source and WordPress core! Register Now →

How to Create a REST API in Codeigniter with Basic Authentication

Updated on September 14, 2021

6 Min Read

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 apps deployed on any PHP web hosting.

rest api codeigniter

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.

CodeIgniter Hosting on Managed Cloud Servers

Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.

Choose your provider (Google, Amazon, Vultr, DigitalOcean), select server size according to your needs and click the Launch button.

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.

PHP Hosting: Best PHP 7 & PHP 5.6 Web Hosting

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 to set up authentication for a REST API in CodeIgniter, including creating four API calls for data manipulation. The beauty of CodeIgniter lies in its streamlined approach to building APIs. For developers seeking a hosting environment optimized for CodeIgniter applications, CodeIgniter Hosting solutions can provide additional efficiency gains. These providers may offer pre-configured settings or streamlined deployment processes specifically for CodeIgniter, allowing you to focus on building your API.

Share your opinion in the comment section. COMMENT NOW

Share This Article

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.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now