How to Create a REST API in Codeigniter with Basic Authentication



A REST API is a web service which uses HTTP methods likes GET, PUT, POST, DELETE for data manipulation over the cross platforms. We will build a PHP Rest Api Using codeignitor.

Question- What is API?

Answer - API Stands for Application Programming interface (to know more about Click here

Question - What is REST in REST API?

Answer - REST stands for Representational State Transfer. 

You can download the codeignitor from here - https://codeigniter.com/download


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:





  1. CREATE TABLE `tbl_user` (  
  2.  `user_id` int(11) NOT NULL,  
  3.  `user_name` varchar(40) NOT NULL,  
  4.  `user_password` varchar(40) NOT NULL,  
  5.  `user_type` varchar(15) NOT NULL  
  6. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;  



Setting up Libraries and Permissions



A REST API is a web service which uses HTTP methods likes GET, PUT, POST, DELETE for data manipulation over the cross platforms. We will build a PHP Rest Api Using codeignitor.

Question- What is API?

Answer - API Stands for Application Programming interface (to know more about Click here 

Question - What is REST in REST API?

Answer - REST stands for Representational State Transfer. 

You can download the codeignitor from here - https://codeigniter.com/download


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:





  1. CREATE TABLE `tbl_user` (  
  2.  `user_id` int(11) NOT NULL,  
  3.  `user_name` varchar(40) NOT NULL,  
  4.  `user_password` varchar(40) NOT NULL,  
  5.  `user_type` varchar(15) NOT NULL  
  6. ) 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. Paste the following code in it.

Setup Authentication and API Key

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.

  1. RewriteEngine On
  2. RewriteCond %{REQUEST_FILENAME} !-f
  3. RewriteCond %{REQUEST_FILENAME} !-d
  4. RewriteRule ^(.*)$ index.php/$1 [L]

Setup Authentication and API Key

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

 

  1. CREATE TABLE `keys` (
  2. `id` int(11) NOT NULL,
  3. `key` varchar(40) NOT NULL,
  4. `level` int(2) NOT NULL,
  5. `ignore_limits` tinyint(1) NOT NULL DEFAULT '0',
  6. `is_private_key` tinyint(1) NOT NULL DEFAULT '0',
  7. `ip_addresses` text,
  8. `date_created` int(11) NOT NULL
  9. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

  1. CREATE TABLE `logs` (
  2. `id` int(11) NOT NULL,
  3. `uri` varchar(255) NOT NULL,
  4. `method` varchar(6) NOT NULL,
  5. `params` text,
  6. `api_key` varchar(40) NOT NULL,
  7. `ip_address` varchar(45) NOT NULL,
  8. `time` int(11) NOT NULL,
  9. `rtime` float DEFAULT NULL,
  10. `authorized` varchar(1) NOT NULL,
  11. `response_code` smallint(3) DEFAULT '0'
  12. ) 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



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

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

To this

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

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

  1. $config['rest_enable_keys'] = TRUE;
  2. $config['rest_logs_table'] = 'logs';
  3. $config['rest_auth'] = 'basic';
  4. $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.

  1. <?php
  2. defined('BASEPATH') OR exit('No direct script access allowed');
  3. require(APPPATH.'/libraries/REST_Controller.php');
  4. class Api extends REST_Controller
  5. {
  6. public function __construct() {
  7. parent::__construct();
  8. $this->load->model('user_model');
  9. }
  10. public function user_get(){
  11. $r = $this->user_model->read();
  12. $this->response($r);
  13. }
  14. public function user_put(){
  15. $id = $this->uri->segment(3);
  16. $data = array('name' => $this->input->get('name'),
  17. 'pass' => $this->input->get('pass'),
  18. 'type' => $this->input->get('type')
  19. );
  20. $r = $this->user_model->update($id,$data);
  21. $this->response($r);
  22. }
  23. public function user_post(){
  24. $data = array('name' => $this->input->post('name'),
  25. 'pass' => $this->input->post('pass'),
  26. 'type' => $this->input->post('type')
  27. );
  28. $r = $this->user_model->insert($data);
  29. $this->response($r);
  30. }
  31. public function user_delete(){
  32. $id = $this->uri->segment(3);
  33. $r = $this->user_model->delete($id);
  34. $this->response($r);
  35. }
  36. }

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

  1. <?php
  2. defined('BASEPATH') OR exit('No direct script access allowed');
  3. /**
  4. *
  5. */
  6. class User_model extends CI_Model
  7. {
  8. public function read(){
  9. $query = $this->db->query("select * from `tbl_user`");
  10. return $query->result_array();
  11. }
  12. public function insert($data){
  13. $this->user_name = $data['name']; // please read the below note
  14. $this->user_password = $data['pass'];
  15. $this->user_type = $data['type'];
  16. if($this->db->insert('tbl_user',$this))
  17. {
  18. return 'Data is inserted successfully';
  19. }
  20. else
  21. {
  22. return "Error has occured";
  23. }
  24. }
  25. public function update($id,$data){
  26. $this->user_name = $data['name']; // please read the below note
  27. $this->user_password = $data['pass'];
  28. $this->user_type = $data['type'];
  29. $result = $this->db->update('tbl_user',$this,array('user_id' => $id));
  30. if($result)
  31. {
  32. return "Data is updated successfully";
  33. }
  34. else
  35. {
  36. return "Error has occurred";
  37. }
  38. }
  39. public function delete($id){
  40. $result = $this->db->query("delete from `tbl_user` where user_id = $id");
  41. if($result)
  42. {
  43. return "Data is deleted successfully";
  44. }
  45. else
  46. {
  47. return "Error has occurred";
  48. }
  49. }
  50. }

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.

Source - https://www.cloudways.com/blog/rest-api-in-codeigniter/


Please Share this course

It Looks like you have completed your course!! We have created Online series based on the above content. You can give a test and check your skill.




Be a Part of CollegeSpike by giving your precious comment here and help us in improving our content.