In this tutorial I am going to show you how we can work with RESTful or REST webservice in Codeigniter framework.

You may like also Working with RESTful services in Codeigniter – POST example, Working with RESTful services in Codeigniter – PUT example 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.

You may read the section on REST API for Codeigniter https://philsturgeon.uk/codeigniter/2009/06/03/REST-implementation-for-CodeIgniter/

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. Dump some data into table contact

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','https://roytuts.com','4517895621');

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

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

modify also <root directory>/application/config/database.php

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

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

<?php

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

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

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

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

    function contacts_get() {
        $contacts = $this->cm->get_contact_list();

        if ($contacts) {
            $this->response($contacts, 200);
        } else {
            $this->response(NULL, 404);
        }
    }

    function contact_get() {
        if (!$this->get('id')) {
            $this->response(NULL, 400);
        }

        $contact = $this->cm->get_contact($this->get('id'));

        if ($contact) {
            $this->response($contact, 200); // 200 being the HTTP response code
        } else {
            $this->response(NULL, 404);
        }
    }

}
  • is used to return GET variables from either a query string like this index.php/restgetcontroller/contact?id=1 or can be set in the more CodeIgniter’s way with index.php/restgetcontroller/contact/id/1.

In the method, we are picking up a ?id=XX and passing it to the model. If data is found we send it to the $this->response() function with a status 200. If nothing is found, return no body and a 404 to say nothing was found.

Step 5. Create a model file ContactModel.php under <project 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 get_contact_list() {
        $query = $this->db->get($this->contact);
        if ($query) {
            return $query->result();
        }
        return NULL;
    }

    function get_contact($id) {
        $query = $this->db->get_where($this->contact, array("contact_id" => $id));
        if ($query) {
            return $query->row();
        }
        return NULL;
    }

}

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

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

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: GET

URL: http://localhost/ci_3_1_0/index.php/restgetcontroller/contacts

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

Output:

[
	{
		"contact_id": "1",
		"contact_name": "S Roy",
		"contact_address": "https://roytuts.com",
		"contact_phone": "1234578960"
	},
	{
		"contact_id": "2",
		"contact_name": "S Roy",
		"contact_address": "https://roytuts.com",
		"contact_phone": "1234578960"
	},
	{
		"contact_id": "3",
		"contact_name": "S Roy",
		"contact_address": "https://roytuts.com",
		"contact_phone": "5454544574"
	},
	{
		"contact_id": "4",
		"contact_name": "S Roy",
		"contact_address": "https://roytuts.com",
		"contact_phone": "4578912360"
	},
	{
		"contact_id": "5",
		"contact_name": "S Roy",
		"contact_address": "https://roytuts.com",
		"contact_phone": "8945761254"
	},
	{
		"contact_id": "6",
		"contact_name": "S Roy",
		"contact_address": "https://roytuts.com",
		"contact_phone": "4587961235"
	},
	{
		"contact_id": "7",
		"contact_name": "S Roy",
		"contact_address": "https://roytuts.com",
		"contact_phone": "1254897652"
	},
	{
		"contact_id": "12",
		"contact_name": "S Roy",
		"contact_address": "https://roytuts.com",
		"contact_phone": "4517895621"
	}
]

If you change as, $[‘rest_default_format’]=’xml’ at <root directory>/application/config/rest.php

<?xml version="1.0" encoding="utf-8"?>
<xml>
<item>
  <contact_id>1</contact_id>
  <contact_name>S Roy</contact_name>
  <contact_address>https://roytuts.com</contact_address>
  <contact_phone>1234578960</contact_phone>
</item>
<item>
  <contact_id>2</contact_id>
  <contact_name>S Roy</contact_name>
  <contact_address>https://roytuts.com</contact_address>
  <contact_phone>1234578960</contact_phone>
</item>
<item>
  <contact_id>3</contact_id>
  <contact_name>S Roy</contact_name>
  <contact_address>https://roytuts.com</contact_address>
  <contact_phone>5454544574</contact_phone>
</item>
<item>
  <contact_id>4</contact_id>
  <contact_name>S Roy</contact_name>
  <contact_address>https://roytuts.com</contact_address>
  <contact_phone>4578912360</contact_phone>
</item>
<item>
  <contact_id>5</contact_id>
  <contact_name>S Roy</contact_name>
  <contact_address>https://roytuts.com</contact_address>
  <contact_phone>8945761254</contact_phone>
</item>
<item>
  <contact_id>6</contact_id>
  <contact_name>S Roy</contact_name>
  <contact_address>https://roytuts.com</contact_address>
  <contact_phone>4587961235</contact_phone>
</item>
<item>
  <contact_id>7</contact_id>
  <contact_name>S Roy</contact_name>
  <contact_address>https://roytuts.com</contact_address>
  <contact_phone>1254897652</contact_phone>
</item>
<item>
  <contact_id>12</contact_id>
  <contact_name>S Roy</contact_name>
  <contact_address>https://roytuts.com</contact_address>
  <contact_phone>4517895621</contact_phone>
</item>
</xml>

Method: GET

URL: http://localhost/ci_3_1_0/index.php/restgetcontroller/contact?id=1

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

Output:

{
	"contact_id": "1",
	"contact_name": "S Roy",
	"contact_address": "https://roytuts.com",
	"contact_phone": "1234578960"
}

If you change as, $[‘rest_default_format’]=’xml’ at <root directory>/application/config/rest.php

<?xml version="1.0" encoding="utf-8"?>
<xml>
<contact_id>1</contact_id>
<contact_name>S Roy</contact_name>
<contact_address>https://roytuts.com</contact_address>
<contact_phone>1234578960</contact_phone>
</xml>

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

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

Leave a Reply

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