Working With RESTful Services In Codeigniter 3 – POST Example

Introduction

In this tutorial I am going to show you how you can work with RESTful or REST webservice in Codeigniter framework. I will build a REST API for HTTP POST method. The HTTP POST method is used to create a new resource in server side.

Related Posts:

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

MySQL 5.x – 8.0.26, Please go through Setup RESTful service with Codeigniter

Project Directory

It’s assumed that you have setup Apache, PHP and Codeigniter in Windows system.

Now I will create a project root directory called codeIgniter-rest-api-post the Apache server’s htdocs folder.

Now move all the directories and files from CodeIgniter framework into codeIgniter-rest-api-post directory.

I may not mention the project root directory in subsequent sections and I will assume that I am talking with respect to the project root directory.

MySQL Table

Create a MySQL table contact under database roytuts. This table stores information for contact address details. For MySQL version 5.x, use the following table structure.

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;

If you are using MySQL version 8.x then use the following table structure:

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

Dump some data into table contact. You need to test your example about “working with restful services in codeigniter – put example” and for that you need some data in the database table. Therefore I am 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','https://roytuts.com','1234567890');

Autoload Configuration

You need some configurations, such as, auto-loading for helpers to avoid loading every time you need to use.

Modify application/config/autoload.php file for auto-loading libraries and helper functions.

This one time auto-loading gives flexibility to uniformly use the helpers and libraries anywhere throughout the application without loading repeatedly.

For my example I am auto-loading databaseurlfile.

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('url', 'file');
$autoload['libraries'] = array('database');

Database Configurations

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' => 'root',
'database' => 'roytuts',
'dbdriver' => 'mysqli',

Controller Class

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

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

<?php

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

require_once 'Format.php';
require_once 'RestController.php';

use chriskacerguis\RestServer\RestController;

/**
 * Description of RestPostController
 *
 * @author https://roytuts.com
 */
class RestPostController extends RestController {
	
	function __construct() {
        parent::__construct();
		$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.

Model Class

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);
    }

}

Testing REST API POST Example

Now run the application on apache http server. Or deploy the application using CLI mode. I have strated application in CLI mode and application deployed at localhost in 8000 port.

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:8000/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"
}

Visual representation of the above test case:

codeigniter 3 rest api post

Check the database table, you will see one new row has been added with below data.

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

Visual representation of the above added data:

codeigniter 3 rest services

Hope you got an idea how to work with REST API POST method.

Source Code

Download

1 thought on “Working With RESTful Services In Codeigniter 3 – 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.

Leave a Reply

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