Working with RESTful Services using CodeIgniter

In this tutorial, we will learn that “Simple way to create RESTful Services using CodeIgniter”. RESTful web services are lightweight, highly scalable and maintainable and are very commonly used to create APIs for web-based applications. There are many resources are fetched from the server using web service like images, videos, web pages, data etc. Resources are manipulated using a fixed set of four operations: PUT, GET, POST, and  DELETE. PUT. Web services are supported multiple types of response format as like JSON, XML, HTML.

If you didn’t know how to create PHP Restful API without Any Rest Framework Dependency you can visit our previous post.

Now let’s started and learn How to easily create web service using simple CodeIgniter framework. We will learn this tutorial using five simple steps as given below,

1. Create Database And Tables.
2. Configure CodeIgniter.
3. Create A REST APIs Controllers And Models.
4. Perform Operations Like GET, POST, PUT, DELETE.
5. Testing APIs.

1. Create Database And Tables.

Before proceeding first of all you need to create one database. Let’s take an example of Product Management so create “product_db” to store data related to different products. Use the following query to creating the database.

1     CREATE DATABASE IF NOT EXISTS `product_db`;

Once database created successfully create “product_detail” table inside “product_db” to store all the product data. Use following query to create “product_detail” table.

123456 CREATE TABLE IF NOT EXISTS `product` (     `product_id` INT NOT NULL AUTO_INCREMENT ,     `product_name` VARCHAR(30) NOT NULL ,     `product_price` INT NOT NULL ,     `product_qty` INT NOT NULL ,      PRIMARY KEY (`product_id`)) ENGINE = InnoDB;

2. Configure CodeIgniter.

As we all know, We are creating the web service in PHP using MVC Framework so we need to configure CodeIgniter for that. I have created project named “rest_api_ci” so we need to configure the path of our project.

Goto Open “application/config” folder and open config.php file. Set your newly created project’s path into $config[‘base_url’].

$config[‘base_url’] = ‘http://localhost/rest_api_ci/’;

Now Open “autoload.php” file from same directory and setup some configuration variables one by one.

Set libraries variable value as database.

$autoload[‘libraries’] = array(‘database’);

Set helper class in the same file.

$autoload[‘helper’] = array(‘url’);

Set model class name into a model variable. [We will create this model class in next steps]

$autoload[‘model’] = array(‘Rest_api_mo’);

Now Open “database.php” files from the same directory and set your database name, username and password. Use following lines of code for this setup.

123456789101112131415161718192021222324 $active_group = ‘default’; $query_builder = TRUE;  $db[‘default’] = array( ‘dsn’ => ”, ‘hostname’ => ‘localhost’, ‘username’ => ‘root’, ‘password’ => ”, ‘database’ => ‘product_db’, ‘dbdriver’ => ‘mysqli’, ‘dbprefix’ => ”, ‘pconnect’ => FALSE, ‘db_debug’ => (ENVIRONMENT !== ‘production’), ‘cache_on’ => FALSE, ‘cachedir’ => ”, ‘char_set’ => ‘utf8’, ‘dbcollat’ => ‘utf8_general_ci’, ‘swap_pre’ => ”, ‘encrypt’ => FALSE, ‘compress’ => FALSE, ‘stricton’ => FALSE, ‘failover’ => array(), ‘save_queries’ => TRUE );

Now all the CodeIgniter configurations are completed. Let’s move to next step.

3. Create A REST APIs Controllers And Models.

Goto ‘application/controllers’ directory and create new file named “Rest_api.php”. Copy and paste following code into “Rest_api.php” file.

1234567891011121314151617181920212223242526272829303132333435363738394041<?phpdefined(‘BASEPATH’) OR exit(‘No direct script access allowed’);require(APPPATH.’/libraries/REST_Controller.php’);class rest_api extends CI_Controller {  public function index() { $this->load->view(‘rest_api’); } public function alldata() { $res=$this->Rest_api_mo->alldata_mo(); echo json_encode($res); } public function insert() { $data=$this->input->post();  $res=$this->Rest_api_mo->insert_mo($data); echo json_encode($res); } public function update() { $data=$this->input->get(); //print_r($data); $res=$this->Rest_api_mo->update_mo($data); echo json_encode($res); } public function delete() { $data=$this->input->get(); //print_r($data); $res=$this->Rest_api_mo->delete_mo($data); echo json_encode($res); }}

Above is the controllers to perform all database operations like fetch, insert, update, delete, using REST API. Now we need to create a model class to perform all these operations.

Goto “application/models” directory and create “Rest_api_mo.php” and add following code lines.

12345678<?phpdefined(‘BASEPATH’) OR exit(‘No direct script access allowed’); class Rest_api_mo extends CI_Model { // In next step here we will add all functions related to database operation }

This is model files and in this file, we will write the code of all database operations next step.

4. Perform Operations Like GET, POST, PUT, DELETE.

Now step by step we can write the code of all database operations into “Rest_api.mo.php” file.

POST :

To insert the data into database server using POST API call write the following function into “Rest_api_mo.php”.

1234567891011121314151617 function insert_mo($data){ $name=$data[‘product_name’]; $price=$data[‘product_price’]; $qty=$data[‘product_qty’];   $res=$this->db->query(“INSERT into product_detail(product_name,product_price,product_qty) values(‘$name’,’$price’,’$qty’)”); if($res) { $res=”Record Inserted!!!!”; } else{ $res=”Something Wrong ..”; } return $res; }

GET :

To fetch all records from the product table using GET API call write the following function into “Rest_api_mo.php”.

12345 function alldata_mo() { $res=$this->db->query(“SELECT * from product_detail”)->result_array(); return $res; }

PUT :

To update particular records of the product table using PUT API call write the following function into “Rest_api_mo.php”.

123456789101112131415161718 function update_mo($data) { $name=$data[‘product_name’]; $price=$data[‘product_price’]; $qty=$data[‘product_qty’]; $id=$data[‘product_id’];  $res=$this->db->query(“UPDATE product_detail set product_name=’$name’,product_price=’$price’,product_qty=’$qty’ where product_id=’$id'”);  if($res) { $res=”Record Updated !!!!”; } else{ $res=”Something Wrong ..”; } return $res; }

DELETE :

To delete particular records of the product table using DELETE API call write the following function into “Rest_api_mo.php”.

1234567891011121314 function delete_mo($data) { $id=$data[‘product_id’];  $res=$this->db->query(“DELETE from product_detail where product_id=’$id'”); if($res) { $res=”Record Deleted!!!!”; } else{ $res=”Something Wrong ..”; } return $res; }

Now all the coding-related part is done. So here we have written four different functions to learn four types of API call [GET, POST, PUT, DELETE]. Following is the full source code of “Rest_api_mo.php” file.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859<?phpdefined(‘BASEPATH’) OR exit(‘No direct script access allowed’); class Rest_api_mo extends CI_Model {  function insert_mo($data){ $name=$data[‘product_name’]; $price=$data[‘product_price’]; $qty=$data[‘product_qty’];   $res=$this->db->query(“INSERT into product_detail(product_name,product_price,product_qty) values(‘$name’,’$price’,’$qty’)”); if($res) { $res=”Record Inserted!!!!”; } else{ $res=”Something Wrong ..”; } return $res; } function alldata_mo() { $res=$this->db->query(“SELECT * from product_detail”)->result_array(); return $res; } function update_mo($data) { $name=$data[‘product_name’]; $price=$data[‘product_price’]; $qty=$data[‘product_qty’]; $id=$data[‘product_id’];  $res=$this->db->query(“UPDATE product_detail set product_name=’$name’,product_price=’$price’,product_qty=’$qty’ where product_id=’$id'”); if($res) { $res=”Record Updated !!!!”; } else{ $res=”Something Wrong ..”; } return $res; } function delete_mo($data) { $id=$data[‘product_id’];  $res=$this->db->query(“DELETE from product_detail where product_id=’$id'”); if($res) { $res=”Record Deleted!!!!”; } else{ $res=”Something Wrong ..”; } return $res; }}

5. Testing APIs.

Now test the newly created APIs using any Web Service Tester tool. We prefer POSTMAN REST Client tools for API Testing. Open the POSTMAN REST Client and select request method [GET, POST, PUT, DELETE], specify URL and arguments.

Method 1:

GET URL: http://localhost/rest_api_ci/rest_api/alldata

Arguments: Not Required.

RESTful Services using CodeIgniter

Method 2:

POST URL: http://localhost/rest_api_ci/rest_api/insert

Arguments: product_name, product_price, and product_qty.

RESTful Services using CodeIgniter

Method 3:

PUT URL: http://localhost/rest_api_ci/rest_api/update

Arguments : product_id,product_name,product_price and product_qty.

RESTful Services using CodeIgniter

Method 4:

DELETE URL: http://localhost/rest_api_ci/rest_api/delete

Arguments: product_id.

RESTful Services using CodeIgniter

Leave a comment