Chat with us, powered by LiveChat

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.

New Save and Scale This Summer. Get 30% OFF for the First 2 Months. Promo: SCALEINSUMMER AVAIL NOW

How to Create a REST API in Codeigniter with Basic Authentication

May 18, 2017

6 Min Read
Reading Time: 6 minutes

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.

Advanced Laravel Hosting For 5x REST API Performance

Speed Up Your App Performance With Our Powerful Laravel Hosting Now

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


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

mv CodeIgniter-develop codeigniter
rm index.php

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

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:



 `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




 `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'


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.

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

class Api extends REST_Controller

       public function __construct() {

       public function user_get(){
           $r = $this->user_model->read();
       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);

       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);
       public function user_delete(){
           $id = $this->uri->segment(3);
           $r = $this->user_model->delete($id);


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


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'];



           return 'Data is inserted successfully';




           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));



           return "Data is updated successfully";




           return "Error has occurred";



   public function delete($id){


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



           return "Data is deleted successfully";




           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.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Launch PHP websites without the worry of Server Management.

Pre-Installed Optimized Stack with Git, Composer & SSH

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

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

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!