Introduction

In this tutorial 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 – PUT example, Codeigniter GET example with REST service and Working with RESTful services in Codeigniter – DELETE example

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.

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 POST: Create a new resource or resources.

Prerequisites

Please go through Setup RESTful service with Codeigniter

Example

Step 1. Create a MySQL table contact under database roytuts.

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=13 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

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

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

Step 3. Modify also <project’s root directory>/application/config/database.php.

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

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

Notice the function name suffixed by _post because we are going to make HTTP POST request. The actual URI will be without _post(add_contact).

<?php
use Restserver\Libraries\REST_Controller;

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

require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';

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

	use REST_Controller {
		REST_Controller::__construct as private __resTraitConstruct;
	}
	
	function __construct() {
        parent::__construct();
		$this->__resTraitConstruct();
		$this->load->model('ContactModel', 'cm');
    }

    function add_contact_post() {
        $contact_name = $this->post('contact_name');
        $contact_address = $this->post('contact_address');
        $contact_phone = $this->post('contact_phone');
        
        $result = $this->cm->add_contact($contact_name, $contact_address, $contact_phone);

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

}
  • is an alias for $this->input->post() which is CodeIgniter’s method to access $_POST variables with XSS protection.

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

<?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 add_contact($contact_name, $contact_address, $contact_phone) {
        $data = array('contact_name' => $contact_name, 'contact_address' => $contact_address, 'contact_phone' => $contact_phone);
        $this->db->insert($this->contact, $data);
    }

}

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

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

Method: POST

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

URL: http://localhost/ci_3_1_0/index.php/restpostcontroller/add_contact

Body: {“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 8. Check the database table, you will see one new row has been added with below data.

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

Thanks for reading.

Tags:

3 thoughts on “Working with RESTful services in Codeigniter – POST example

  1. Thank you so much! I’m just starting to work with APIs and this tutorial was really useful for me. Really well explained. Thanks again.

  2. I am getting error

    ( ! ) Fatal error: Class ‘REST_Controller’ not found in C:\wamp64\www\codeIgniter\application\controllers\RestPostController.php on line 14
    Call Stack
    # Time Memory Function Location
    1 0.0000 264744 {main}( ) …\index.php:0
    2 0.0000 338976 require_once( ‘C:\wamp64\www\codeIgniter\system\core\CodeIgniter.php’ ) …\index.php:315
    3 0.0326 1411288 require_once( ‘C:\wamp64\www\codeIgniter\application\controllers\RestPostController.php’ ) …\CodeIgniter.php:411
    A PHP Error was encountered
    Severity: Error

    Message: Class ‘REST_Controller’ not found

    Filename: controllers/RestPostController.php

    Line Number: 14

    Backtrace:

Leave a Reply

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