Create A REST API In Codeigniter With Basic Authentication
Tags: webdev, codeigniter, hosting
Published: 2018-03-28 09:22:31

---
title: Create A REST API In Codeigniter With Basic Authentication
published: true
description: 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
cover_image: https://thepracticaldev.s3.amazonaws.com/i/xzrzgc3vi5b06yaunu3j.jpg
tags: #webdev,#codeigniter,#hosting
---
The CodeIgniter RESTful API is a set of simple, modular helpers that can be easily integrated into your CodeIgniter projects, allowing you to create customizable RESTful APIs that suit all your needs. The package includes helpers for database manipulation, JSON Web Token generation, validation and signing, authentication methods, methods for accessing resources using a URI, as well as some utility methods that will help streamline your workflow.

##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.


![Alt text](https://thepracticaldev.s3.amazonaws.com/i/ueg7okh8thprev2cay9s.jpg)


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.

##Install 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:

![Alt text](https://thepracticaldev.s3.amazonaws.com/i/7keo603sxo7f3p0fucjb.gif)

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

![Alt text](https://thepracticaldev.s3.amazonaws.com/i/wru2oimg53a46vnva785.png)

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

![Alt text](https://thepracticaldev.s3.amazonaws.com/i/jr8zv6r0h3hrc57866eh.png)

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

```
![Alt text](https://thepracticaldev.s3.amazonaws.com/i/aboc65oj1uqksllfswtt.png)

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.


![Alt text](https://thepracticaldev.s3.amazonaws.com/i/rq5p7bvxlrv3xpm9sfei.png)

##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.

![Alt text](https://thepracticaldev.s3.amazonaws.com/i/ob18w3vdqltxoj3rfswj.png)

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;
```
![Alt text](https://thepracticaldev.s3.amazonaws.com/i/3qusu3qmslufj10wzm1q.png)

##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.

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


![Alt text](https://thepracticaldev.s3.amazonaws.com/i/bpqoqmv4jq7nral1w1ar.png)


![Alt text](https://thepracticaldev.s3.amazonaws.com/i/ww4t68tlp2kvts66pxp5.png)

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:

![Alt text](https://thepracticaldev.s3.amazonaws.com/i/jvpq2jrahiuvcquagdk9.png)


![Alt text](https://thepracticaldev.s3.amazonaws.com/i/3pidxgsb6plhnyxzas5x.png)

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:

![Alt text](https://thepracticaldev.s3.amazonaws.com/i/42bbctvf05lw6ock2mvn.png)

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:

![Alt text](https://thepracticaldev.s3.amazonaws.com/i/gtmm2bppe3dytc0euu0n.png)

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:

![Alt text](https://thepracticaldev.s3.amazonaws.com/i/an85wb90aodczgul0nh2.png)

Conclusion

So, this is how i can create Rest API in PHP. I hope it was helpful for you.If you need any help with the code or the idea of implementing your own RESTful API in Codeigniter, do leave a comment below.