In the tutorial, working with restful services in codeigniter – put example, I am going to show you how we can work with RESTful or REST webservice in Codeigniter framework.

You may also like the Working with RESTful services in Codeigniter – POST example,  Codeigniter GET example with REST service and Working with RESTful services in Codeigniter – DELETE example

Introduction

The most important concept in REST is resources, which are identified by global IDs — typically using URIs. Client applications use HTTP methods (GET/ POST/ PUT/ DELETE) to manipulate the resource or collection of resources. A RESTful Web service is implemented using HTTP and the principles of REST. Typically, a RESTful Web service should define the following aspects:

The base/root URI for the Web service such as http://<host>/<appcontext/contextpath>/<url pattern>/<resources>.
The MIME type of the response data supported, which are JSON/XML/TEXT/HTML etc.
The set of operations supported by the service. (for example, POST, GET, PUT or DELETE).

Methods

HTTP methods are mapped to CRUD (create, read, update and delete) actions for a resource. Although you can make slight modifications such as making the PUT method to create or update, the basic patterns are listed as follows.

HTTP GET: Get/List/Retrieve an individual resource or a collection of resources.
HTTP POST: Create a new resource or resources.
HTTP PUT: Update an existing resource or collection of resources.
HTTP DELETE: Delete a resource or collection of resources.

Prerequisites

Please go through Setup RESTful service with Codeigniter

Example

Step 1. Create a MySQL table contact under database roytuts. This table stores information for contact address details.

USE `roytuts`;

/*Table structure for table `contact` */

DROP TABLE IF EXISTS `contact`;

CREATE TABLE `contact` (
  `contact_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `contact_name` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `contact_address` varchar(150) COLLATE utf8_unicode_ci NOT NULL,
  `contact_phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`contact_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Modify <root directory>/application/config/autoload.php file for auto-loading html, url, file, form and database.

It is not mandatory but if you auto-load the libraries or helper classes which are repeatedly used in many places throughout the application then these classes are available anywhere and it simplifies your life.

$autoload['helper'] = array('html', 'url', 'file', 'form');
$autoload['libraries'] = array('database');

Step 2. Dump some data into table contact. We need to test our example on “working with restful services in codeigniter – put example” and for that we need some data in the database table. Therefore we are dumping some sample data into the table. If your data are coming from different sources then you don’t need it.

insert  into 
`contact`(`contact_id`,`contact_name`,`contact_address`,`contact_phone`) 
values 
(1,'S Roy','https://roytuts.com','1234578960'),
(2,'S Roy','https://roytuts.com','1234578960'),
(3,'S Roy','https://roytuts.com','5454544574'),
(4,'S Roy','https://roytuts.com','4578912360'),
(5,'S Roy','https://roytuts.com','8945761254'),
(6,'S Roy','https://roytuts.com','4587961235'),
(7,'S Roy','https://roytuts.com','1254897652'),
(12,'S Roy','Earth','1234567890');

Step 3. Modify also <root directory>/application/config/database.php. This modification is required in order to establish the connection with database and performing database queries.

'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'roytuts',
'dbdriver' => 'mysqli',

Step 4. Create a controller file RestPutController.php under <project root>/application/controllers with the following source code.

Here notice how we have declare the method name update_contact_put(), the actual method name is update_contact but as we are going to apply http put operation so we are appending _put to the actual method in order to get benefit of the built-in API’s functionality otherwise we might have to handled the http put operation in some other way.

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

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

/**
 * Description of RestPutController
 *
 * @author https://roytuts.com
 */
class RestPutController extends REST_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('ContactModel', 'cm');
    }

    function update_contact_put() {
        $contact_id = $this->put('contact_id');
        $contact_name = $this->put('contact_name');
        $contact_address = $this->put('contact_address');
        $contact_phone = $this->put('contact_phone');

        $result = $this->cm->update_contact($contact_id, $contact_name, $contact_address, $contact_phone);

        if ($result === FALSE) {
            $this->response(array('status' => 'failed'));
        } else {
            $this->response(array('status' => 'success'));
        }
    }

}

Step 5. Create a model file ContactModel.php under <project root>/application/models with the following source code.

The below model function gets the input values from controller class and update the contact information in database.

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Description of ContactModel
 *
 * @author https://roytuts.com
 */
class ContactModel extends CI_Model {

    private $contact = 'contact';

    function update_contact($contact_id, $contact_name, $contact_address, $contact_phone) {
        $data = array('contact_name' => $contact_name, 'contact_address' => $contact_address, 'contact_phone' => $contact_phone);
        $this->db->where('contact_id', $contact_id);
        $this->db->update($this->contact, $data);
    }

}

Step 6. Modify file <project root>/application/config/routes.php file.

We need to call the default controller otherwise we won’t be able to run our application. That’s why we are pointing the default controller as REST service controller.

If you have any other controller then you can make that controller as a default controller and then you can use the REST service controller from any link or button.

$route['default_controller'] = 'restputcontroller';

Step 7. Now run the application on apache http server.

Step 8. Use the REST Client in Firefox browser to test the REST service.

Method: PUT

Headers: Add Custom Header as name = Content-Type, value=application/json

URL: http://localhost/ci_3_1_0/index.php/restputcontroller/update_contact

Body: {“contact_id”:”12″, “contact_name”:”S Roy”, “contact_address”:”https://roytuts.com”, “contact_phone”:”1234567890″}

$[‘rest_default_format’]=’json’ at <root directory>/application/config/rest.php

Output:

{
    "status": "success"
}

Step 9. Check the database table, you will see the row has been updated with below data.

Here you see the contact_id with 12 has been updated. If you check the row value in the initial data then you can find that the column values were different for this row.

contact_id	contact_name	contact_address	      contact_phone
    12	           S Roy	https://roytuts.com	1234567890

Thanks for reading.

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

1 thought on “Working with RESTful services in Codeigniter – PUT example

  1. $contact_id = $this->put(‘contact_id’);
    print_r( $contact_id);
    result:NULL

    when i submit the json from postman it results NULL kindly let me know how to use $this->put() method

Leave a Reply

Your email address will not be published. Required fields are marked *