How to create RESTful web services in codeigniter

Spread the love

RESTful web services in codeigniter

RESTful web services are a way of communication among computer systems. REST services are based on REST architecture. World wide web has resources like images, videos, web pages and other business information. Web service clients use URIs to request these resources. Response to the web service request can be in JSON, HTML, XML or some other format. In a previous tutorial, you learned about SOAP web services in php using nusoap. This tutorial is about how to create a RESTful web services in CodeIgniter. A resource cane be created, modified or deleted using HTTP methods like GET, POST, PUT or DELETE.

To create restful web services in CodeIgniter, following tasks would be performed.

1. Create a books database and table

2. Add sample data to table

3. Setup a CodeIgniter application

4. Create a RESTful library file, a model and an API controller to the application.

5. Create API methods to fetch a book information via ISBN or fetch all books records.

6. Create add a new book, update book and delete a book record methods to API

7. Test API with Google Chrome Postman extension

Create a books database and table

In order to create RESTful web services in CodeIgniter first, you have to install PHP, MySQL. If you have not installed PHP and MySql, then visit WAMP or XAMPP website, download and install PHP MySQL. After installation, open PhpMyAdmin. Click on SQL tab and execute queries given below.

--
-- Database: `dbbookstore`
--
CREATE DATABASE IF NOT EXISTS dbbookstore DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;

USE dbbookstore;

-- --------------------------------------------------------

--
-- Table structure for table "tbl_books"
--

CREATE TABLE tbl_books (
  id int(11) NOT NULL,
  name varchar(500) NOT NULL,
  price float(8,2) NOT NULL,
  author varchar(300) NOT NULL,
  category varchar(250) NOT NULL,
  language varchar(100) NOT NULL,
  ISBN varchar(40) NOT NULL,
  publish_date date NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=latin1;

--
-- Dumping data for table "tbl_books"
--

INSERT INTO tbl_books (id, name, price, author, category, language, ISBN, publish_date) 
VALUES
(1, 'Red Hat Enterprise Linux 6 Administration', 50.00, 'Sander van', 'Computer Science', 'en', '984-1234-12341234', '2013-12-05'),
(2, 'Design Patterns: Elements of Reusable Object-Oriented Software ', 15.11, 'Ralph Johnson, John Vlissides, Grady Booch', 'Computer Science', 'en', '978-0201633610', '2016-03-01'),
(3, 'Machine Learning for Absolute Beginners\r\n', 10.36, 'Oliver Theobald', 'Computer Science', 'en', '123-58679-654', '2016-08-01'),
(4, 'Python Crash Course: A Hands-On, Project-Based Introduction to Programming', 21.58, ' Eric Matthes', 'Programming', 'en', '659-8546-324', '2015-11-30'),
(5, 'Data Structures and Algorithms in Java', 102.65, 'Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser', 'Computer Science', 'en', ' 978-1118777788', '2014-06-23'),
(6, 'Star Wars: Darth Vader Vol. 1: Vader', 26.54, 'Kieron Gillen', 'Comic Novels', 'en', '485-6582-658', '2015-09-16'),
(7, 'Star Wars Vol. 1: Skywalker Strikes', 16.23, 'Jason Aron', 'Novels', 'en', '159-7539-985', '2011-04-11'),
(8, 'Phonics for Kindergarten, Grade K ', 6.32, 'Carson-Dellosa Publishing ', 'Education', 'en', '412-6548-7854', '2016-08-10'),
(9, 'Astrophysics for People in a Hurry ', 9.95, 'Astrophysics for People in a Hurry ', 'Science', 'en', '654-71235-654', '2010-10-02'),
(10, 'Let''s Review Algebra I', 8.54, 'Gary Rubinstein (Author) ', 'Science', 'en', '978-1438009854', '2006-03-24');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_books`
--
ALTER TABLE tbl_books
  ADD PRIMARY KEY (id);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_books`
--
ALTER TABLE tbl_books
  MODIFY id int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=13

restful web services in codeigniter

Create a codeigniter application

As we have to create RESTful web services in codeigniter; so latest codeigniter version is required. Visit codeigniter website and download latest version of codeigniter and unzip it. Create a folder restful-services-in-codeigniter in htdocs or wwwroot folder of your php installation.

Copy the contents of CodeIgniter folder including application and system folder. Rename application folder to appx and system folder to sysx.

Open index.php file and change line no. 100 to

$system_path = 'sysx';

and line no 117 to

$application_folder = 'appx';

Open config.php file in config folder and go to line 26 and change base_url  to

$config['base_url'] = 'http://localhost';

On Line 38 change index_page to

$config['index_page'] = '';

Next, change

$config['uri_protocol'] = "AUTO"

to

$config['uri_protocol'] = "REQUEST_URI"

Now, Go to rool folder of project e.g restful-services-in-codeigniter and create a file .htaccess

Add code given below into the file.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Normally when you access a CodeIgniter controller URL in the browser, it is of the form http://localhost/projectname/index.php/welcome so in order to remove index.php  from the URL, settings are changed as above.

Open database.php file in appx/config path and change database settings. Update hostnameusername, password and database name according to your MySQL installation.

Download REST controller and related files

Visit Github CodeIgniter rest server  repository and download following files and copy to project directory as described below. Adding these files to project is necessary to create RESTful web services in CodeIgniter. Open libraries folder and create a file REST_controller.php and add code from this file. Create a file Format.php and add code from this link.

HTTP methods

We are going to use following HTTP methods.

GET

Get method is used to fetch data about a resource. In CodeIgniter $this->get() method is used to get parameters from URL or Query String.

POST

POST method is used to create a new resource. $this->post() method in CI is used to access values sent by client.

PUT

To update an existing resource PUT method is used. CodeIgniter’s $this->put() method is used to access values.

DELETE

To delete a resource this method is used. In CodeIgniter $this->delete() method is used.

Creating a model for book

In this tutorial on RESTful web services in codeigniter, we have to create a model for books. Open Models folder and add a file Book_model.php. Add following code into this file.

<?php
  class Book_model extends CI_Model {
       
      public function __construct(){
          
        $this->load->database();
        
      }
      
      //API call - get a book record by isbn
      public function getbookbyisbn($isbn){  

           $this->db->select('id, name, price, author, category, language, ISBN, publish_date');

           $this->db->from('tbl_books');

           $this->db->where('isbn',$isbn);

           $query = $this->db->get();
           
           if($query->num_rows() == 1)
           {

               return $query->result_array();

           }
           else
           {

             return 0;

          }

      }

    //API call - get all books record
    public function getallbooks(){   

        $this->db->select('id, name, price, author, category, language, ISBN, publish_date');

        $this->db->from('tbl_books');

        $this->db->order_by("id", "desc"); 

        $query = $this->db->get();

        if($query->num_rows() > 0){

          return $query->result_array();

        }else{

          return 0;

        }

    }
   
   //API call - delete a book record
    public function delete($id){

       $this->db->where('id', $id);

       if($this->db->delete('tbl_books')){

          return true;

        }else{

          return false;

        }

   }
   
   //API call - add new book record
    public function add($data){

        if($this->db->insert('tbl_books', $data)){

           return true;

        }else{

           return false;

        }

    }
    
    //API call - update a book record
    public function update($id, $data){

       $this->db->where('id', $id);

       if($this->db->update('tbl_books', $data)){

          return true;

        }else{

          return false;

        }

    }

}

This book model class is extended from CI_model class. In constructor database class is loaded.

$this->load->database();

Fetch book by ISBN method for restful web services in codeigniter

getbookbyisbn method is defined. This method fetches a book record based on ISBN. $this->db->get() method returns a result object. num_rows contains rows in result. If there is a record then result array is returned.

Fetch all books method for restful web services in codeigniter

To fetch all books from a database getallbooks method is defined. This method selects and returns all books records.

Delete a book method for restful web services in codeigniter

Delete method is defined for deleting a book record. It accepts id. Id is passed to $this->db->where. $this->db->delete method is called with tbl_book.  If query is executed successfully record is deleted and true is returned.

Add a book method for restful web services in codeigniter

To add a new record to database, Add method is created. Add method accepts $data array containing values for all columns in tbl_books table. $data array and table name tbl_books are passed to $this->db->insert method. On successful insertion true is returned.

Update a book method for restful web services in codeigniter

To update an existing book record, update method is defined. This method accepts id of record and a data array of values to be updated. In $this->db->where clause id is passed and then in $this->db->update data and table name are passed. Data is updated successfully and true is returned otherwise false is returned.

Adding API controller

Let us create an API is required so that clients can access API methods. Open controllers folder. Add a file API.php. Add the code below in this file.

<?php

require(APPPATH.'/libraries/REST_Controller.php');
 
class Api extends REST_Controller{
    
    public function __construct()
    {
        parent::__construct();

        $this->load->model('book_model');
    }

    //API - client sends isbn and on valid isbn book information is sent back
    function bookByIsbn_get(){

        $isbn  = $this->get('isbn');
        
        if(!$isbn){

            $this->response("No ISBN specified", 400);

            exit;
        }

        $result = $this->book_model->getbookbyisbn( $isbn );

        if($result){

            $this->response($result, 200); 

            exit;
        } 
        else{

             $this->response("Invalid ISBN", 404);

            exit;
        }
    } 

    //API -  Fetch All books
    function books_get(){

        $result = $this->book_model->getallbooks();

        if($result){

            $this->response($result, 200); 

        } 

        else{

            $this->response("No record found", 404);

        }
    }
     
    //API - create a new book item in database.
    function addBook_post(){

         $name      = $this->post('name');

         $price     = $this->post('price');

         $author    = $this->post('author');

         $category  = $this->post('category');

         $language  = $this->post('language');

         $isbn      = $this->post('isbn');

         $pub_date  = $this->post('publish_date');
        
         if(!$name || !$price || !$author || !$price || !$isbn || !$category){

                $this->response("Enter complete book information to save", 400);

         }else{

            $result = $this->book_model->add(array("name"=>$name, "price"=>$price, "author"=>$author, "category"=>$category, "language"=>$language, "isbn"=>$isbn, "publish_date"=>$pub_date));

            if($result === 0){

                $this->response("Book information coild not be saved. Try again.", 404);

            }else{

                $this->response("success", 200);  
           
            }

        }

    }

    
    //API - update a book 
    function updateBook_put(){
         
         $name      = $this->put('name');

         $price     = $this->put('price');

         $author    = $this->put('author');

         $category  = $this->put('category');

         $language  = $this->put('language');

         $isbn      = $this->put('isbn');

         $pub_date  = $this->put('publish_date');

         $id        = $this->put('id');
         
         if(!$name || !$price || !$author || !$price || !$isbn || !$category){

                $this->response("Enter complete book information to save", 400);

         }else{
            $result = $this->book_model->update($id, array("name"=>$name, "price"=>$price, "author"=>$author, "category"=>$category, "language"=>$language, "isbn"=>$isbn, "publish_date"=>$pub_date));

            if($result === 0){

                $this->response("Book information coild not be saved. Try again.", 404);

            }else{

                $this->response("success", 200);  

            }

        }

    }

    //API - delete a book 
    function deleteBook_delete()
    {

        $id  = $this->delete('id');

        if(!$id){

            $this->response("Parameter missing", 404);

        }
         
        if($this->book_model->delete($id))
        {

            $this->response("Success", 200);

        } 
        else
        {

            $this->response("Failed", 400);

        }

    }


}

In the code above REST_Controller.php file is included from libraries folder.

require(APPPATH.'/libraries/REST_Controller.php');

An API class is added and is extended from REST_Controller class. In class constructor, parent constructor is called and book model is loaded using $this->load_model method.

class Api extends REST_Controller{ 
      public function __construct() { 
          parent::__construct(); 
          $this->load->model('book_model'); 
      }
  
    ....
 
 }

Defining methods with get, post, put and delete

In the code above note that HTTP methods get, post, put and delete are used with each method name. But when these methods are called from a client get, post, put and delete are not used.

To fetch record from a database _get is added with function name but to create a new resource or to update _post or _put and _delete is used with delete method.

Controller method to get books by ISBN

To get a book information by ISBN the function bookByISBN is created. You can view _get added with function name.

$this->get is used to get variable values from URL or query string. If no ISBN is specified by client then a response code of 400 is sent back to client otherwise this ISBN is passed to book_model‘s method getbookbyisbn.

Result is returned to client using $this->response method with status code 200. Otherwise 404 status code is returned with message invalid ISBN.

function bookByIsbn_get(){

     $isbn = $this->get('isbn'); 

     if(!$isbn){ 

       $this->response("No ISBN specified", 400); 

       exit; 

      } 
      
      $result = $this->book_model->getbookbyisbn( $isbn ); 

      if($result){ 

           $this->response($result, 200); 

           exit;

      }else{ 

           $this->response("Invalid ISBN", 404); 

           exit; 
        } 

      }

Get all books information method

To fetch all books information books_get method is created. Model’s getallbooks method returns information about all books from database. In case of success result is returned with status code 200 , otherwise error is returned with status code 404.

//API - Fetch All books 

function books_get(){ 

   $result = $this->book_model->getallbooks(); 

   if($result){ 

      $this->response($result, 200); 

   } else{ 

      $this->response("No record found", 404); 

   }

}

Add a new book using API method

To create a new book, addBook_post method is created with HTTP POST method. Client passes book information using post method from web service client. Using $this->post values are assigned to variables. If any of the value is missing response code 400 or bad request is send back with message to client.

Data array is passed to model’s add method. If data is saved into database and a response code 200 is sent back to user with a success message, Other wise a 400 request code this sent back to user.

//API - create a new book item in database.

function addBook_post(){ 
    
    $name = $this->post('name'); 
    
    $price = $this->post('price'); 
    
    $author = $this->post('author');       
    
    $category = $this->post('category'); 
    
    $language = $this->post('language'); 
    
    $isbn = $this->post('isbn'); 

    $pub_date = $this->post('publish_date'); 

    if(!$name || !$price || !$author || !$price || !$isbn || !$category){ 

       $this->response("Enter complete book information to save", 400); 

     }else{ 
    
        $result = $this->book_model->add(array("name"=>$name, "price"=>$price, "author"=>$author, "category"=>$category, "language"=>$language, "isbn"=>$isbn, "publish_date"=>$pub_date)); 

       if($result === 0){ 

            $this->response("Book information could not be saved. Try again.", 404); 

       }else{ 
            
            $this->response("success", 200); 

       }

    }
 
}

Update book method

In order to update a book information updatebook_put method is created. put is HTTP method to update a resource. All required values are assigned to variables using $this->put method.

If any of required parameters are not sent by client a response code 400 with a message is sent to client. Otherwise book_model‘s update method is called and data array is passed with book id.  On successful update success message with status code 200 is sent to user otherwise a 404 response is sent back.

//API - update a book information

function updateBook_put(){ 

    $name     = $this->put('name'); 

    $price    = $this->put('price'); 

    $author   = $this->put('author'); 

    $category = $this->put('category'); 

    $language = $this->put('language'); 

    $isbn     = $this->put('isbn'); 

    $pub_date = $this->put('publish_date'); 

    $id       = $this->put('id'); 

    if(!$id || !$name || !$price || !$author || !$price || !$isbn || !$category){ 

        $this->response("Enter complete book information to save", 400); 

    }else{ 

        $result = $this->book_model->update($id, array("name"=>$name, "price"=>$price, "author"=>$author, "category"=>$category, "language"=>$language, "isbn"=>$isbn, "publish_date"=>$pub_date)); 
 
        if($result === 0){ 

             $this->response("Failed to save Book information. Try again.", 404); 

        }else{
 
             $this->response("success", 200); 
        }
 
     } 
 
 }

Delete a book method

To delete a book record using API method deleteBook_delete() method is created. In the method $id is assigned using $this->delete() method. If there is no $id then a 404 response is sent to client. Otherwise $book_model‘s delete method is called. On success status code 200 otherwise a status code 400 is returned.

//API - delete a book 

  function deleteBook_delete() { 

          $id = $this->delete('id'); 
 
          if(!$id){ 

              $this->response("Parameter missing", 400); 

          } 
         
          if($this->book_model->delete($id)) { 

              $this->response("Success", 200); 

          } else { 
           
              $this->response("Failed", 404); 
          }
   }

Testing web service using Postman Chrome extension

Web services can be consumed by multiple clients.  A client can be a PHP, ASP.Net application or a mobile app. In this tutorial creating restful web services in codeigniter we are going to use google chrome’s Postman extension.

Open Google Chrome browser. Click Window menu in top menu and click Extensions. Click on the link Get more Extensions in bottom. In Search bar on left side enter postman and click search. In available extensions search results click on Postman and click Add to Chrome. After installation click on Launch button. Let us test web service.

Postman Google Chrome extension

You can see in this extension user can select HTTP method, Enter request URL or can add params.

restful web services in codeigniter

 

Selecting HTTP Methods

If you click on the drop down with GET parameter value, other HTTP methods that can also be selected.

restful web services in codeigniter

Address bar URL and Parameters

In image below you can see  address bar for adding web service URL with a button to add parameters. Clicking on Send button, web service request is sent to server.

restful web services in codeigniter

Testing get books by ISBN method

Open postman and add following URL in address bar. Here port 8888 is used by MAMP on a MAC system. Do not use port if If your WAMP or MAMP installation do not have it.  Select GET from methods drop down.

http://localhost:8888/restful-services-in-codeigniter/api/bookbyIsbn
Next an ISBN is added as a parameter. Click on Params button. In Key textbox enter isbn and in values textbox enter 978-0071492478.

Click on Send button and on success, result is sent back to browser.

restful web services in codeigniter

Testing 400 Bad Request

If you do not specify a parameter while calling to a web service a bad request is returned.

restful web services in codeigniter

Testing 404 not found request

If an invalid ISBN is entered  then a 404 Not Found status code is returned with a message.

restful web services in codeigniter

Testing Get All Books method

To get all books records, you need to call books method, notice we are not using _get with this method call. In postman add the URL below in address bar.

restful web services in codeigniter

As there are no parameters; so click on Send button. Request is sent to server, in response all book records are returned as a JSON a object

restful web services in codeigniter

 

You can see in picture above, result is returned from web service.

Testing add a new book using API method

In order to test add new book method, let us first view existing records in database. Currently there are 10 records in database.

restful web services in codeigniter

Now in Postman select POST from HTTP methods drop down. Add following URL in address bar.

http://localhost:8888/restful-services-in-codeigniter/api/addbook

restful web services in codeigniter

Adding a book using POST method, parameters are sent as part of body. Click on Body tab below address bar and select x-www-form-urlencoded radio button.

There are text boxes for keys and values. Add all parameters for the new book. Key is the name of column and value contains the data to be saved. Like name= Complete Reference ASP.NET MVC and so on. After adding data, Click Send button. If insertion is successful a success message is returned.

restful web services in codeigniter

You can see below newly added record in database at id = 11

restful web services in codeigniter

Testing  update book method

To update record of an existing book updateBook method is called using PUT HTTP method. Select PUT from HTTP methods drop down and add this URL in address bar.

http://localhost:8888/restful-services-in-codeigniter/api/updatebook
. Click on body tag and select x-www-form-urlencoded radio button. See existing book record at id =1.

restful web services in codeigniter - update record - existing record

In Postman add new book record in key value boxes under body tag. Add id key with value 1. After adding book information click Send button. You can see success message and updated information.

restful web services in codeigniter

You can view the updated record below.

restful web services in codeigniter

Testing delete a book method

To delete a book from database using API deleteBook method is usedOpen postman and add following URL in 

http://localhost:8888/restful-services-in-codeigniter/api/deletebook
.
From drop down select delete method.

Suppose you want to delete a book with  id =11 from database. So in key value boxes add id as key and 11 as value. Click on Send button. Success message is returned from server after deletion of book.

restful web services in codeigniter

Summary

To summarize, in this tutorial you have learned to create restful web services in CodeIgniter. Then how to call and test web services using a client such as Postman Google Chrome extension. Hope this tutorial is helpful for you.

Please leave your feedback and comments. Follow us on twitter to stay updated on the upcoming articles and tutorials. You can download source code of the tutorial from this link

If  GIT is installed on your system, you can Clone repository. On command line go to the root directory (www or wwwroot) of your WAMP, MAMP or XAMPP directory.

Type following command.

 git clone git@github.com:programmer-blog/restful-services-in-codeigniter.git

To download code on your system. Click on Clone or download link. Next, click on Download Zip link on right side of the repository.

 

Related Articles:

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Save

Check Also

generate a pdf using php

How to Generate a PDF using php

Spread the loveLast updated:24th April, 2021How to Generate a PDF using php In the modern …