• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
seegatesite header

Seegatesite.com

Seegatesite.com - Programming Tutorial , Sharing , How and Learn Together

  • TOOLS
    • Bootstrap Navbar Online Generator
    • Customize Sidebar Menu Bootstrap 3
    • Bootstrap Demo
  • ADVERTISE
  • CATEGORIES
    • Android
    • Blogging Tips
    • Database
    • CSS
    • Info Gadget
    • Javascript
    • Linux
    • PHP
    • Various
    • WordPress
  • Q&A
  • PHP
  • JAVASCRIPT
  • JQUERY
  • ANGULAR
  • WORDPRESS
  • SEO
  • REACT
🏠 » PHP » CodeIgniter Tutorial How To Make Rest API ( Server And Client )

CodeIgniter Tutorial How To Make Rest API ( Server And Client )

By Sigit Prasetya Nugroho ∙ July 25, 2017 ∙ PHP ∙ 25 Comments

Share : TwitterFacebookTelegramWhatsapp

This CodeIgniter tutorial will discuss how to create Codeigniter REST API from both server and client-side. CodeIgniter has several libraries that support and easy to create REST APIs application. Currently, REST API becomes a communication method that must be used for web-based applications. CodeIgniter as the most straightforward PHP framework to create REST API. Read the following PHP rest API tutorial.

REST (REpresentational State Transfer) is a communication method architecture that is often applied in the development of web-based services. REST API is run through the HTTP / HTTPS protocol. REST APIs involves the process of reading certain web pages that generate JSON format. After going through a specific definition process, consumers can access the data presented by the server-side.

The uniqueness of REST is the communication between client and server facilitated by some unique operational types (verbs) and Universal Resource Identifiers (URIs) for each resource. Each verb (GET, POST, PUT, DELETE) has special operational meaning to avoid ambiguity. Okay, we started the CodeIgniter tutorial how to create a REST API with a simple example.

Read another article: Rest API And HTTP Methods (GET, POST, PUT, DELETE) Using Slim Framework And PHP

Table of Contents

  • 1 CodeIgniter Tutorial Creating a Simple REST API Server
    • 1.1 Download and Install CodeIgniter
    • 1.2 Create Database And Table
    • 1.3 Installing the CodeIgniter Rest Server Library
    • 1.4 Create a web service
    • 1.5 Test The REST API CodeIgniter using Postman Plugin
  • 2 How To Create a Simple Rest Client in CodeIgniter
    • 2.1 Create CURL Class
    • 2.2 Create CodeIgniter Model
    • 2.3 Create CodeIgniter Controller
  • 3 Bonus Source Code ( CodeIgniter Rest API Server Project)

CodeIgniter Tutorial Creating a Simple REST API Server

Download and Install CodeIgniter

We will skip this section because I’ve covered the complete CodeIgniter tutorial in the article “Simple CRUD Apps With Codeigniter Tutorial For Beginners.” Please change your project folder as “codeigniterapi” folder.

Create Database And Table

The database and tables used still the same as the previous article “pos” database and “m_item” table. To shorten the time, please create a new MySQL database with the name “pos” and copy the following script to create “m_item” table and fill the dummy data.

1
2
3
4
5
6
7
8
9
10
11
12
CREATE TABLE 'm_item' (
  'id_item' varchar(6) NOT NULL,
  'item_name' varchar(100) DEFAULT NULL,
  'note' text,
  'stock' decimal(10,2) DEFAULT '0.00',
  'price' int(14) DEFAULT '0',
  'unit' varchar(4) DEFAULT 'PCS',
  PRIMARY KEY ('id_item'),
  UNIQUE KEY 'unik' ('item_name')
)
insert  into 'm_item'('id_item','item_name','note','stock','price','unit') values ('PB0001','Razor Blade','best razor blade in the world',9.00,12000,'PCS');
insert  into 'm_item'('id_item','item_name','note','stock','price','unit') values ('PB0002','Muscle Face','for build body',10.00,50000,'PCS');

Installing the CodeIgniter Rest Server Library

  • Please download the library codeigniter-restserver.
  • Copy the “application/libraries/Format.php” and “application/libraries/REST_Controller.php” files into your “application/libraries/” folder. Copy the rest.php from “application/config/rest.php” and paste in your application’s configuration folder.
  • Copy the language’s folder into application’s folder

Create a web service

Create a web service to handle request data from “m_item” table. Make the request handling using the codeigniter-restserver library is quite easy, we just need to add an “index_” prefix to the function for each request header.

Related Articles :

  • Simple CRUD Apps With Codeigniter Tutorial For Beginners
  • How To Remove Index php Url Path Codeigniter
  • PHP Codeigniter MVC Concept For Dummies With Simple Example

1
2
3
4
5
6
7
8
9
10
11
class Books extends REST_Controller
{
  public function index_get()
  {
    // Display all books
  }
  public function index_post()
  {
    // Create a new book
  }
}

Create a controller named Api.php, which is the resource of the web service that will handle the data management request from the m_item table. Please copy the following script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
require APPPATH . '/libraries/REST_Controller.php';
class api extends REST_Controller {
 
function __construct($config = 'rest') {
parent::__construct($config);
}
 
function index_get() {
$id = $this->get('id');
if ($id == '') {
$product = $this->db->get('m_item')->result();
} else {
$this->db->where('id_item', $id);
$product = $this->db->get('m_item')->result();
}
$this->response($product, 200);
}
 
function index_post() {
$data = array(
'id_item' => $this->input->post('item_id'),
'item_name' => $this->input->post('item_name'),
'note' => $this->input->post('item_note'),
'stock' => $this->input->post('item_stock'),
'price' => $this->input->post('item_price'),
'unit' => $this->input->post('item_unit')
);
$insert = $this->db->insert('m_item', $data);
if ($insert) {
$this->response($data, 200);
} else {
$this->response(array('status' => 'fail', 502));
}
}
 
function index_put() {
$id = $this->put('item_id');
$data = array(
'item_name' => $this->put('item_name'),
'note' => $this->put('note'),
'stock' => $this->put('stock'),
'price' => $this->put('price'),
'unit' => $this->put('unit')
);
$this->db->where('id_item', $id);
$update = $this->db->update('m_item', $data);
if ($update) {
$this->response($data, 200);
} else {
$this->response(array('status' => 'fail', 502));
}
}
 
function index_delete() {
$id = $this->delete('item_id');
$this->db->where('id_item', $id);
$delete = $this->db->delete('m_item');
if ($delete) {
$this->response(array('status' => 'success'), 201);
} else {
$this->response(array('status' => 'fail', 502));
}
}
}

Test The REST API CodeIgniter using Postman Plugin

To test the script above, you can use the POSTMAN plugin on chrome browser or Firefox. In my tutorial, I use chrome browser, Please install POSTMAN.

The first test is to make a request to the server, to display all data from “m_item” table with GET method header like the following picture.

Codeigniter Tutorial Create Rest Api With Get Header URI

The second is send request on the server to save a new data to the “m_item” table with POST method. Please follow the picture below.

Codeigniter Tutorial How To Create Restfull Api For Beginner

The third is send request to the server to update the data table “m_item” with PUT method as shown below.

Send PUT Header To Rest Api Codeigniter Tutorial

The last test is send request to the rest server to delete the data on the “m_item” table with DELETE method as shown below.

Codeigniter Tutorial How Send DELETE Header To Rest Api Server With Postman

Until this step, CodeIgniter Tutorial to create a simple API server has been completed; the next step will explain how to access the API from the client side

How To Create a Simple Rest Client in CodeIgniter

To be able to access the server API, surely we must create a Rest Client to access the APIs. Here’s the tutorial.

Note: The REST Client project continuing from the previous project in the article “Simple CRUD Apps With Codeigniter Tutorial For Beginners.” Please download the project first.

Create CURL Class

Create a new PHP class to access the API server with the name Restclient.php in the folder “mycodeigniter/application/libraries/Restclient.php”. Copy the following script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
 
class Restclient{
      var $API ="";
      function __construct() {
        $this->API="http://localhost/codeigniterapi/index.php/api";
      }
 
      function get($param = null)
      {
          if($param == null)
          {
              $curl_handle = curl_init();
              curl_setopt($curl_handle, CURLOPT_URL, $this->API);
              curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
              $buffer = curl_exec($curl_handle);
              return $buffer;
          }else{
             $params = '?';
              foreach ($param as $key => $value){
                 $params .= $key.'='.$value.'&';
             }
             $curl_handle = curl_init();
             curl_setopt($curl_handle, CURLOPT_URL, $this->API.$params);
             curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
             $buffer = curl_exec($curl_handle);
             return $buffer;
         }
     }
 
     function post($array)
     {
          $curl_handle = curl_init();
          curl_setopt($curl_handle, CURLOPT_URL, $this->API);
          curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
          curl_setopt($curl_handle, CURLOPT_POST, 1);
          curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $array);
          $buffer = curl_exec($curl_handle);
          return $buffer;
      }
 
      function put($array)
      {
           $curl_handle = curl_init();
           curl_setopt($curl_handle, CURLOPT_URL, $this->API);
           curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
           curl_setopt($curl_handle, CURLOPT_POSTFIELDS, http_build_query($array));
           curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, "PUT");
           $buffer = curl_exec($curl_handle);
           return $buffer;
      }
 
      function delete($id)
      {
         $array = array("item_id" => $id);
         $curl_handle = curl_init();
         curl_setopt($curl_handle, CURLOPT_URL, $this->API);
         curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($curl_handle, CURLOPT_POSTFIELDS, http_build_query($array));
         curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, "DELETE");
         $buffer = curl_exec($curl_handle);
         return $buffer;
      }
}

Create CodeIgniter Model

Modify the model on product_model.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
class Product_model extends CI_Model {
 
var $API ="";
function __construct() {
parent::__construct();
$this->API="http://localhost/codeigniterapi/index.php";
}
 
function list_product(){
return json_decode($this->restclient->get());
}
 
function product($id){
$params = array('id'=>  $id);
return json_decode($this->restclient->get($params),true);
}
 
function save($array)
{
$this->restclient->post($array);
}
 
function update($array)
{
$this->restclient->put($array);
}
 
function delete($id)
{
$this->restclient->delete($id);
}
}
?>

Create CodeIgniter Controller

Change the Product.php controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
class Product extends  CI_Controller {
public function index(){
$this->load->model('product_model');
$data['product_list'] = $this->product_model->list_product();
$data['title'] = "Product";
$this->load->view('product_list',$data);
}
 
public function add()
{
$this->load->view('product_form');
}
 
public function save()
{
$array_item = array(
'item_id' => $this->input->post('item_id'),
'item_name' => $this->input->post('item_name'),
'item_note' => $this->input->post('item_note'),
'item_stock' => $this->input->post('item_stock'),
'item_price' => $this->input->post('item_price'),
'item_unit' => $this->input->post('item_unit')
);
$this->load->model('product_model');
$save = $this->product_model->save($array_item);
if($save)
{
$this->session->set_flashdata('hasil','Insert Data Berhasil');
}else
{
$this->session->set_flashdata('hasil','Insert Data Gagal');
}
redirect('product');
}
 
public function save_edit()
{
$array_item = array(
'item_id' =>$this->input->post('item_id'),
'item_name' => $this->input->post('item_name'),
'note' => $this->input->post('item_note'),
'stock' => $this->input->post('item_stock'),
'price' => $this->input->post('item_price'),
'unit' => $this->input->post('item_unit')
);
$this->load->model('product_model');
$this->product_model->update($array_item);
redirect('product');
}
 
public function edit(){
$this->load->model('product_model');
$data['product'] = $this->product_model->product($this->uri->segment(3))[0];
$this->load->view('product_edit',$data);
}
 
public function delete()
{
$id = $this->uri->segment(3);
$this->load->model('product_model');
$this->product_model->delete($id);
redirect('product');
}
}

Test the script and run on your browser  http://localhost/mycodeigniter/index.php/product, and the result must be like the following picture

Codeigniter Tutorial How To Create Rest Api Client

Until this step, CodeIgniter Tutorial REST API SERVER And CLIENT is done. You can download the entire project from the download link below

Bonus Source Code ( CodeIgniter Rest API Server Project)

Download the example in the link below

[sociallocker id=58]

Url : http://wp.me/a65Dpx-VS

Password : seegatesite.com

[/sociallocker]

Thus my article about CodeIgniter Tutorial How To Make Rest API ( Server And Client ) hope useful 🙂

Another PHP Related Post :

  • Tutorial Create Simple POS Using ReactJS And Laravel Lumen Part 1
  • How To Replace String With Another String In PHP
  • Login Page – Tutorial CRUD Client and API Server Using JQuery And Lumen Part 2
  • Tutorial CRUD Client and API Server Using JQuery And Lumen Part 1
  • How To Solve Problems Illegal mix of collations (latin1_swedish_ci,IMPLICIT) In Laravel
  • How To Resolve No ‘Access-Control-Allow-Origin’ Header In Lumen

Avatar for Sigit Prasetya Nugroho

About Sigit Prasetya Nugroho

This site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.

Reader Interactions

Comments

  1. Avatar for HelmiHelmi says

    April 11, 2018 at 3:48 am

    Hi,
    Nice tutorial and it helps me a lot. Can you guide how to generate API key and put in login in Rest Client to access Rest Server? In short, how to make authentication from Rest Client to Rest Server?

    Thank you.

    Reply
    • Avatar for Sigit Prasetya NugrohoSigit Prasetya Nugroho says

      April 12, 2018 at 1:43 am

      Dear helmi,

      you can implement API key with JWT (Json Web Token)

      read more here https://seegatesite.com/php-json-web-token-tutorial-for-beginners/

      Reply
  2. Avatar for junejune says

    April 25, 2018 at 2:43 am

    got a problem when i test it on POSTMAN error 404

    Reply
    • Avatar for Sigit Prasetya NugrohoSigit Prasetya Nugroho says

      April 27, 2018 at 1:19 am

      404 is not found..check again your code

      Reply
  3. Avatar for Alex LopezAlex Lopez says

    May 11, 2018 at 4:27 am

    Hello I need help:
    ———————————————–
    A PHP Error was encountered
    Severity: Parsing Error
    Message: syntax error, unexpected ‘[‘
    Filename: libraries/REST_Controller.php
    Line Number: 165
    Backtrace:
    ———————————————–

    libraries/REST_Controller.php…… line 165
    protected $methods = [];

    Reply
    • Avatar for Sigit Prasetya NugrohoSigit Prasetya Nugroho says

      May 15, 2018 at 1:45 am

      Please check your php version 🙂

      Reply
  4. Avatar for AnuAnu says

    June 13, 2018 at 2:34 pm

    I am getting this error..

    Fatal error: Class ‘Restserver\Libraries\CI_Controller’ not found in C:\Xampp\htdocs\api_testserver\application\libraries\REST_Controller.php on line 22
    A PHP Error was encountered
    Severity: Error

    Message: Class ‘Restserver\Libraries\CI_Controller’ not found

    Filename: libraries/REST_Controller.php

    Line Number: 22

    Backtrace:

    Reply
    • Avatar for Sigit Prasetya NugrohoSigit Prasetya Nugroho says

      June 16, 2018 at 1:41 am

      Please download all entire project in the bottom of article 🙂

      Reply
  5. Avatar for varshavarsha says

    June 25, 2018 at 12:42 pm

    I am also getting this error..

    Fatal error: Class ‘Restserver\Libraries\CI_Controller’ not found in C:\Xampp\htdocs\api_testserver\application\libraries\REST_Controller.php on line 22
    A PHP Error was encountered
    Severity: Error

    Message: Class ‘Restserver\Libraries\CI_Controller’ not found

    Filename: libraries/REST_Controller.php

    Line Number: 22

    Backtrace:

    Reply
    • Avatar for Sigit Prasetya NugrohoSigit Prasetya Nugroho says

      June 25, 2018 at 3:08 pm

      Please download the whole project in the bottom article

      Reply
  6. Avatar for IbrahimIbrahim says

    October 15, 2018 at 4:50 am

    A PHP Error was encountered
    Severity: Error
    Message: Class ‘REST_Controller’ not found
    Filename: controllers/Api.php
    Line Number: 4
    Backtrace:

    Reply
    • Avatar for Sigit Prasetya NugrohoSigit Prasetya Nugroho says

      October 19, 2018 at 2:14 am

      Please download the source code 🙂

      Reply
      • Avatar for SliceSlice says

        November 5, 2018 at 10:26 am

        Mine also Class ‘REST_Controller’ not found but where is the link to download ..but we did what u said first copy Format.php and REST_Controller.php into app/libaries and then rest.php ect these three steps but we are getting error …What is wrong man

        Reply
        • Avatar for Sigit Prasetya NugrohoSigit Prasetya Nugroho says

          November 6, 2018 at 8:07 am

          https://seegatesite.com/wp-content/uploads/2017/07/codeigniter-tutorial-simple-rest-api-client-project-free-download.zip

          pass : seegatesite.com

          Reply
  7. Avatar for SayaSaya says

    December 12, 2018 at 5:28 pm

    I am getting error when I run sql queries.

    4 errors were found during analysis.

    A symbol name was expected! (near “‘id_item'” at position 27)
    At least one column definition was expected. (near “‘id_item'” at position 27)
    Unexpected beginning of statement. (near “6” at position 45)
    Unrecognized statement type. (near “NOT NULL” at position 48)

    heelp me please

    Reply
    • Avatar for Sigit Prasetya NugrohoSigit Prasetya Nugroho says

      December 13, 2018 at 1:26 am

      your code please 🙂

      Reply
  8. Avatar for naufalnaufal says

    January 28, 2019 at 9:04 am

    can i make like this?
    function index_get($a=”, $b=”){}
    and when i call the api, i call like this apisite.com/a/b/

    Reply
    • Avatar for Sigit Prasetya NugrohoSigit Prasetya Nugroho says

      January 29, 2019 at 4:57 am

      Your question is confusing, Please explain in more detail…

      Reply
  9. Avatar for kutukutu says

    March 6, 2019 at 10:11 am

    hi am trying to run the code but i got this error……Message: Invalid argument supplied for foreach()

    Reply
    • Avatar for Sigit Prasetya NugrohoSigit Prasetya Nugroho says

      March 18, 2019 at 3:05 am

      i will check ASAP 🙂

      Reply
  10. Avatar for loncatloncat says

    June 2, 2019 at 10:13 am

    how search data from external API ?

    Reply
    • Avatar for Sigit Prasetya NugrohoSigit Prasetya Nugroho says

      June 6, 2019 at 10:57 am

      using curl

      Reply
  11. Avatar for LoncatLoncat says

    June 2, 2019 at 11:01 am

    I mean search according Product ID

    Reply
    • Avatar for Sigit Prasetya NugrohoSigit Prasetya Nugroho says

      June 6, 2019 at 10:58 am

      please more specific…

      Reply
  12. Avatar for anonymousanonymous says

    June 18, 2019 at 8:51 am

    Your code examples are difficult to read due to no tabs in your formatting. I recommend modifying them.

    Reply
    • Avatar for Sigit Prasetya NugrohoSigit Prasetya Nugroho says

      June 19, 2019 at 3:05 pm

      Thank you for the advice you gave

      Reply

Leave a Reply Cancel reply

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

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Welcome to my Home,

Avatar for Sigit Prasetya NugrohoThis site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.



Popular Articles

Checked checkbox AdminLTE Bootstrap in Jquery

November 4, 2014 By Sigit Prasetya Nugroho 7 Comments

Simple create date format validation with jqueryUI

December 21, 2014 By Sigit Prasetya Nugroho Leave a Comment

Create Simple Progress Bar for Fake Online Generator with Jquery

January 10, 2015 By Sigit Prasetya Nugroho Leave a Comment

22+ Coolest Free Jquery Plugin For Premium Theme

October 3, 2015 By Sigit Prasetya Nugroho Leave a Comment

Easy Build Your Anti Copy Paste Plugin

October 6, 2015 By Sigit Prasetya Nugroho Leave a Comment

Popular Tags

adminlte (15) adsense (13) adsense tips (4) affiliate amazon (13) amazon (12) Android (8) angular (16) angular 4 (12) angular 5 (4) asin grabber (3) Bootstrap (27) codeigniter (5) create wordpress theme (5) crud (8) css (6) free wordpress theme (7) google adsense (4) imacros (4) increase traffic (6) jquery (34) laravel (10) laravel 5 (5) learn android (5) lumen api (4) modal dialog (5) mysql (6) nodeJs (4) optimize seo (4) pdo (6) php (30) plugin (53) pos (8) Publisher Tips (5) react (6) Reactjs (9) SEO (37) theme (17) tutorial angular (5) tutorial angular 4 (6) tutorial javascript (10) tutorial javascript beginners (4) twitter (3) wordpress (18) wordpress plugin (13) XMLRPC (5)




  • About
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms and Conditions

©2022 Seegatesite.com