DEV Community

Cover image for Create A REST API In Codeigniter With Basic Authentication
pardeep
pardeep

Posted on

Create A REST API In Codeigniter With Basic Authentication

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

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

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

Alt text

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

Alt text

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

Enter fullscreen mode Exit fullscreen mode

Alt text

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
Enter fullscreen mode Exit fullscreen mode

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

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

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;
Enter fullscreen mode Exit fullscreen mode

Alt text

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]

Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode
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;
Enter fullscreen mode Exit fullscreen mode

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

Alt text

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

$autoload['libraries'] = array( );
Enter fullscreen mode Exit fullscreen mode

To this

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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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); 
       }
Enter fullscreen mode Exit fullscreen mode

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

       }

   }



}

Enter fullscreen mode Exit fullscreen mode

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

Alt text

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

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

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

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.

Top comments (14)

Collapse
 
zamfir80 profile image
Razvan Zamfir • Edited

I have made a small blogging application in Codeigniter 3. I have recently separated its back-end (dashboard) from the frontend.

I would like to give up on loading views in the frontend and spit-out JSONS instead. Further, I would like to use Vue to handle the frontend (JSON).

The issue is described in detail here. Please give me a hand.

Thanks!

Collapse
 
vimuth7 profile image
vimuth • Edited

Thanks so much I learned a lot from here. And I think we can use wget linux command to get Libraries and config files from codeigniter-restserver. in "Setting up Libraries and Permissions" section you can do this,

cd codeigniter/applications/libraries
wget https://raw.githubusercontent.com/ardisaurus/ci-restserver/master/application/libraries/REST_Controller.php
wget https://raw.githubusercontent.com/chriskacerguis/codeigniter-restserver/master/applic
es/Format.php
cd codeigniter/applications/config
wget https://raw.githubusercontent.com/chriskacerguis/codeigniter-restserver/master/application/config/res
t.php

Here what I have done is downloaded those files with wget command using raw view of those github files

Thanks,
Vimuth

Collapse
 
ulisesescamilla profile image
Ulises Escamilla

Thanks pardeep!,

I have a question and I'm so confused, what's the difference between password on the User's table, the rest_valid_logins in the rest.php file and the API Key in the Key's table. Can you help me please?

Collapse
 
dasuccess profile image
DASUCCESS

Hy, i was hoping you can help me on the current project i am on, i have been trying to write an affiliate code for code igniter 4, affiliate to register under affiliate. once a user is registered a referral link is generated and then other user can use the link to generate there own and register as an affiliate under the first person, can you help with some code to execute this, thanks

Collapse
 
azcodez profile image
azcodez

Thanks Pardeep

Do you have to do route.php?

Thanks
Az

Collapse
 
mikerico profile image
Maicol Romero

thanks for the help bro

Collapse
 
mslabba profile image
Muhammed Shihabudeen Labba

Thanks for the detailed article.

But when I try to access the API even using 'No Auth' it is working.

Collapse
 
emmanuelmuthui profile image
EmmanuelMuthui

I have created my api, but am trying to use the users from database to login as opposed to hardcoding username as admin and password as 1234.

How can i go about it kindly?

Collapse
 
aasiimwedatacare profile image
Asiimwe Apollo

Thanks Pardeep

Collapse
 
ogisetiawan profile image
ogisetiawan

thanks Boom!,

simple module,

Collapse
 
azcodez profile image
azcodez

Thanks Pardeep

Do you know how to add Oauth2.0 to authenticate?

Collapse
 
deogit profile image
deogit

Can you explain what is basic authentication?
Where we can set the admin and password?

Collapse
 
deogit profile image
deogit

Got it!

Just saw it in $config['rest_valid_logins'] = ['admin' => '1234'];

Some comments may only be visible to logged-in visitors. Sign in to view all comments.