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
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.
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 } } |
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.
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.
The third is send request to the server to update the data table “m_item” with PUT method as shown below.
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.
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
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 🙂
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.
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/
got a problem when i test it on POSTMAN error 404
404 is not found..check again your code
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 = [];
Please check your php version 🙂
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:
Please download all entire project in the bottom of article 🙂
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:
Please download the whole project in the bottom article
A PHP Error was encountered
Severity: Error
Message: Class ‘REST_Controller’ not found
Filename: controllers/Api.php
Line Number: 4
Backtrace:
Please download the source code 🙂
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
https://seegatesite.com/wp-content/uploads/2017/07/codeigniter-tutorial-simple-rest-api-client-project-free-download.zip
pass : seegatesite.com
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
your code please 🙂
can i make like this?
function index_get($a=”, $b=”){}
and when i call the api, i call like this apisite.com/a/b/
Your question is confusing, Please explain in more detail…
hi am trying to run the code but i got this error……Message: Invalid argument supplied for foreach()
i will check ASAP 🙂
how search data from external API ?
using curl
I mean search according Product ID
please more specific…
Your code examples are difficult to read due to no tabs in your formatting. I recommend modifying them.
Thank you for the advice you gave