Membuat REST Server di CodeIgniter 3

Ditulis oleh Riedayme
- 0 Komentar
Membuat REST Server di CodeIgniter 3
Sebelumnya saya sudah mengatahui metode apa saja yang dapat digunakan dalam membuat web service maka disini saya akan mencoba untuk menerapkannya dengan codeIgniter 3 menggunakan metode REST.

contoh penerapan API adalah aplikasi web yang ingin dijadikan aplikasi mobile, disini aplikasi mobile akan membutuhkan data dari aplikasi web tersebut, agar data bisa terhubung maka dibutuhkan Web Service sebagai penghubungmya bisa dikatakan API dari dari web tersebut. atau bisa juga anda hanya membuat rest server saja di web tersebut nantinya web tersebut sebagai rest client.

Pengetahuan yang dibutuhkan

  • Mengerti apa itu Web Service
  • Mengerti apa itu REST
  • Mengerti cara penggunaan framework codeigniter
  • Mengerti cara penggunaan phpmyadmin
  • Mengerti cara penggunaan postman

Aplikasi yang dibutuhkan

Library yang dibutuhkan

Langkah Pertama yang dilakukan

Langkah Kerja

1. Membuat Table database mysql di phpmyadmin

masuk kedalam database daily_codeigniter kemudian masukan query sql dibawah ini untuk membuat tabelnya :

CREATE TABLE `tb_quote_post` (
  `id` int(255) NOT NULL,
  `title` text NOT NULL,
  `slug` varchar(255) NOT NULL,
  `image` varchar(255) NOT NULL,
  `time` datetime NOT NULL,
  `updated` datetime NOT NULL,
  `category` varchar(255) NOT NULL,
  `content` longtext NOT NULL,
  `views` int(11) NOT NULL,
  `status` enum('Published','Draft') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Indexes for table `tb_quote_post`
--
ALTER TABLE `tb_quote_post`
  ADD PRIMARY KEY (`id`),
  ADD KEY `permalink` (`slug`),
  ADD KEY `time` (`time`),
  ADD KEY `status` (`status`),
  ADD KEY `category` (`category`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tb_quote_post`
--
ALTER TABLE `tb_quote_post`
MODIFY `id` int(255) NOT NULL AUTO_INCREMENT;

2. Menghubungkan file Library rest server ke file codeigniter 3

  • Extract library rest server dimana saja karena disini kita hanya akan membutuhkan beberapa file saja
  • kemudian pindahkan beberapa file dan folder yang ada didalam folder application ke folder application daily_codeigniter, file tersebut antara lain :
    • config/ldap.php
    • config/rest.php
    • config/hooks.php
    • config/profiler.php
    • helper/db_helper.php
    • hooks/hooks.profiler.php
    • language/indonesia
    • language/english
    • libraries/Format.php
    • libraries/REST_Controller.php
  • dilanjut dengan membuat aplikasi rest servernya

3. Membuat Crud Rest Server

  • buat file controllers dengan nama Quote_Post.php didalam folder api (buat folder api terlebih dahulu) maka pathnya adalah application/controllers/api/Quote_Post.php
  • kemudian isi dengan kode dibawah ini :
<?php  
defined('BASEPATH') OR exit('No Direct Script');


# require REST Library
require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';

# use REST Class
use Restserver\Libraries\REST_Controller;

class Quote_Post extends REST_Controller {

    function __construct(){
        parent::__construct();

        $this->load->model('api/M_Quote_Post');
    }

    public function read_all_get(){ 

        $read = $this->M_Quote_Post->read_all($this->get());

        $this->response($read,REST_Controller::HTTP_OK);
    }

    public function read_by_get(){ 

        $read = $this->M_Quote_Post->read_by($this->get());

        $this->response($read,REST_Controller::HTTP_OK);
    }

    public function post_post(){

        $post = $this->M_Quote_Post->create($this->post());

        $this->response($post, REST_Controller::HTTP_OK);
    }

    public function update_post(){

        $update = $this->M_Quote_Post->update($this->post());

        $this->response($update, REST_Controller::HTTP_OK);
    }

    public function delete_by_get(){

        $delete = $this->M_Quote_Post->delete_by($this->get());

        $this->response($delete, REST_Controller::HTTP_OK);
    }

    public function delete_batch_delete(){

        $delete = $this->M_Quote_Post->delete_batch($this->delete());

        $this->response($delete, REST_Controller::HTTP_OK);
    }    

}
  • Dilanjut membuat file model dengan nama M_Quote_Post.php didalam folder api (buat folder api terlebih dahulu) maka pathnya adalah application/models/api/M_Quote_Post.php
  • kemudian isi dengan kode dibawah ini :
<?php  
defined('BASEPATH') OR exit('No direct script access allowed');

class M_Quote_Post extends CI_Model 
{

    public $table = 'tb_quote_post';
    public $storage_path = 'storage/uploads/';

    public function count(){
        return $this->db->count_all_results($this->table, FALSE);
    }

    public function read_all($data){

        if (!empty($data['order_by']) AND !empty($data['order_type'])) {
            $this->db->order_by($data['order_by'],$data['order_type']);
        }

        $read = $this->db->get($this->table, $data['limit'] , $data['index']);

        if ($read->num_rows() > 0) {

            $extract_data = $this->extract_data($read->result_array(),true);

            $response = array(
             'status' => 'success',
             'content' => $extract_data,
             'row_count' => $this->M_Quote_Post->count()
             );            
        }else {
            $response = array (
                'status' => 'failed',
                'content' => false,
                );
        }

        return $response;        
    }

    public function read_by($data){

        if (empty($data['key']) or empty($data['value'])) {
            $response = array (
                'status' => 'failed',
                'content' => 'require key and value params',
                );

            return $response;
        }else {

            $identity = [$data['key'] => $data['value']];    

            $this->db->db_debug = false;
            $read = $this->db->get_where($this->table,$identity);

            if (empty($read)) {
                $response = array (
                    'status' => 'failed',
                    'content' => 'key not found on table',
                    );

                return $response;
            }

            if ($read->num_rows() > 0) {

                $extract_data = $this->extract_data($read->row_array(),false);

                $response = array(
                    'status' => 'success',
                    'content' => $extract_data,
                    );
            }else {

                $response = array (
                    'status' => 'failed',
                    'content' => 'value '. $data['value'] .' with key '. $data['key'] .' not found',
                    );
            }

            return $response;             
        }       
    }

    public function create($data){


        $post_data = $this->_all_column($data);

        $this->db->insert($this->table,$post_data);

        if ($this->db->affected_rows() > 0) {

            $response = array(
                'status' => 'success',
                'message' => 'success create quote post',
                );
        }else {

            $response = array(
                'status' => 'failed',
                'message' => 'failed create quote post',
                );
        }

        return $response;
    }

    public function update($data){


        $identity = [$data['key'] => $data['value']];

        if (!empty($_FILES['image'])) {
            $delete_image = $this->db->get_where($this->table,$identity)->row_array();

            @unlink($this->storage_path.$delete_image['image']);
            @unlink($this->storage_path.'thumbnail/'.$delete_image['image']);           
        }

        $post_data = $this->_all_column($data);

        $this->db->trans_start();
        $this->db->update($this->table, $post_data, $identity);
        $this->db->trans_complete();

        if ($this->db->affected_rows() > 0) {
            $response = array(
                'status' => 'success',
                'message' => 'success update quote post',
                );
        }else {
            if ($this->db->trans_status() === false) {
                $response = array(
                    'status' => 'failed',
                    'message' => 'failed update quote post',
                    );
            }else {                
                $response = array(
                    'status' => 'success',
                    'message' => 'success update quote post',
                    );
            }
        }   

        return $response;     
    }

    public function delete_by($data) {

        if (empty($data['key']) or empty($data['value'])) {
            $response = array (
                'status' => 'failed',
                'content' => 'require key and value params',
                );

            return $response;
        }else {

            $identity = [$data['key'] => $data['value']]; 

            $this->db->db_debug = false;
            $read = $this->db->get_where($this->table,$identity);

            if (empty($read)) {
                $response = array (
                    'status' => 'failed',
                    'content' => 'key not found on table',
                    );

                return $response;
            }else {

                if ($read->num_rows() > 0) {

                    $read = $read->row_array();

                    @unlink($this->storage_path.$read['image']);
                    @unlink($this->storage_path.'thumbnail/'.$read['image']);        

                    $this->db->delete($this->table,$identity);        

                    if ($this->db->affected_rows() > 0) {

                        $response = array(
                            'status' => 'success',
                            'content' => 'success delete quote post with key ' .$data['key'] . ' and value '. $data['value'],
                            );
                    }else {

                        $response = array(
                            'status' => 'failed',
                            'content' => 'failed delete quote post with key ' .$data['key'] . ' and value '. $data['value'],
                            );
                    }


                }else {

                    $response = array (
                        'status' => 'failed',
                        'content' => 'value '. $data['value'] .' with key '. $data['key'] .' not found',
                        );
                }

                return $response;

            }

        }

    }

    public function delete_batch($data) {

        if (empty($data['key']) or empty($data['value'])) {
            $response = array (
                'status' => 'failed',
                'content' => 'require key and value params',
                );

            return $response;
        }else {

            foreach($data['value'] as $id) {

                $identity = [$data['key'] => $id]; 

                $this->db->db_debug = false;
                $read = $this->db->get_where($this->table,$identity);

                if (empty($read)) {
                    $response = array (
                        'status' => 'failed',
                        'content' => 'key not found on table',
                        );

                    return $response;
                }else {

                    if ($read->num_rows() > 0) {

                        $read = $read->row_array();

                        @unlink($this->storage_path.$read['image']);
                        @unlink($this->storage_path.'thumbnail/'.$read['image']);        

                        $this->db->delete($this->table,$identity);        

                        if ($this->db->affected_rows() > 0) {

                            $response[] = array(
                                'status' => 'success',
                                'content' => 'success delete quote post with key ' .$data['key'] . ' and value '. $id,
                                );
                        }else {

                            $response[] = array(
                                'status' => 'failed',
                                'content' => 'failed delete quote post with key ' .$data['key'] . ' and value '. $id,
                                );
                        }


                    }else {

                        $response[] = array (
                            'status' => 'failed',
                            'content' => 'value '. $id .' with key '. $data['key'] .' not found',
                            );
                    }


                }
            }

            return array(
                'status' => 'success',
                'content' => $response
                );


        }

    }    

    /**
     * 
     * logic progress
     * 
     */
    
    public function _upload($data){

        if (empty($_FILES['image'])) {
            return 'noimage';
            exit;
        }

        #load library upload
        $this->load->library('upload');        

        $config_upload = [
        'upload_path' => $this->storage_path,
        'allowed_types' =>'jpg|png|ico',
        ];

        $this->upload->initialize($config_upload);

        if($this->upload->do_upload('image')){

            $result = array('image' => $this->upload->data());

            $create_thumb = $this->_thumbnail($result['image']['file_name'],$config_upload['upload_path']);
            if ($create_thumb != 'success') {
                echo $create_thumb;
                exit;
            }

            return $result['image']['file_name'];
        }else {
            return 'failed';
        }

    }

    public function _thumbnail($file_data,$path_dir)
    {

        #load library image_lib
        $this->load->library('image_lib');
        $source_path = $path_dir.$file_data;
        $target_path = $path_dir.'thumbnail/';
        $config = array(
          'image_library' => 'gd2',
          'source_image' => $source_path,
          'new_image' => $target_path,
          'maintain_ratio' => TRUE,
          'width' => 320,
          );

        $this->image_lib->clear();
        $this->image_lib->initialize($config);

        if (!$this->image_lib->resize()) {
            return $this->image_lib->display_errors();
        }
        else {

            return 'success';
        }        
    }

    public function _all_column($data){

        # file upload
        $file = $this->_upload($data);

        $prepare_data = array(
            'title' => $data['title'] ,
            'slug' => $data['slug'] ,           
            'time' => $data['time'] ,
            'updated' => $data['updated'] ,
            'category' => $data['category'] ,
            'content' => $data['content'] ,
            'views' => $data['views'] ,
            'status' => $data['status'] ,           
            );


        if ($file !== 'noimage') {
            $prepare_data['image'] = $file;
        }

        $post_data = $prepare_data;

        return $post_data;
    }

    public function extract_data($read,$multiple){
        if ($multiple) {
            foreach ($read as $data) {
                $extract_data[] = array(
                    'id' => $data['id'],                        
                    'title' => $data['title'],
                    'slug' => $data['slug'],
                    'image' => base_url($this->storage_path.$data['image']),
                    'image_thumbnail' => base_url($this->storage_path.'thumbnail/'.$data['image']),                        
                    'time' => $data['time'],
                    'updated' => $data['updated'],
                    'category' => $data['category'],
                    'content' => $data['content'],
                    'views' => $data['views'],
                    'status' => $data['status'],
                    );
            }
        }else {

            $data = $read;

            $extract_data = array(
                'id' => $data['id'],                        
                'title' => $data['title'],
                'slug' => $data['slug'],
                'image' => base_url('storage/uploads/'.$data['image']),
                'image_thumbnail' => base_url('storage/uploads/thumbnail/'.$data['image']),                        
                'time' => $data['time'],
                'updated' => $data['updated'],
                'category' => $data['category'],
                'content' => $data['content'],
                'views' => $data['views'],
                'status' => $data['status'],
                );
        }

        return $extract_data;
    }    

}

4. Membuat Auth Rest Server

agar data tidak dapat diakses secara public maka disini saya membuat sebuah authorization dan sebuah api key, yang nantinya akan digunakan ketika ingin mengakses rest server yang dibuat. untuk langkah membuatnya cukup mudah yaitu :
  • Membuat table api_keys untuk penyimpanan api key, masukan query sql ini untuk membuat table :
-- --------------------------------------------------------

--
-- Table structure for table `api_keys`
--

CREATE TABLE `api_keys` (
  `id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `key` varchar(40) NOT NULL,
  `level` int(2) NOT NULL,
  `ignore_limits` tinyint(1) NOT NULL DEFAULT 0,
  `is_private_key` tinyint(1) NOT NULL DEFAULT 0,
  `ip_addresses` text DEFAULT NULL,
  `date_created` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `api_keys`
--

INSERT INTO `api_keys` (`id`, `user_id`, `key`, `level`, `ignore_limits`, `is_private_key`, `ip_addresses`, `date_created`) VALUES
(1, 1, 'admin', 1, 1, 0, NULL, 0);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `api_keys`
--
ALTER TABLE `api_keys`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `api_keys`
--
ALTER TABLE `api_keys`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
COMMIT;
  • Mengatur konfigurasi file rest.php yang ada didalam folder application/config/rest.php dengan pengaturan sebagai berikut :
    • $config['rest_auth'] = 'basic';
    • $config['auth_source'] = '';
    • $config['rest_valid_logins'] = ['admin' => 'admin']; (ini adalah username dan passwordnya)
    • $config['rest_keys_table'] = 'api_keys';
    • $config['rest_enable_keys'] = TRUE;
    • $config['rest_key_name'] = 'APP_KEY';
  • oke sudah selesai untuk pembuatan rest servernya sekarang coba test dengan menggunakan aplikasi post man

5. Ujicoba Rest Server dengan Postman

  • Buka aplikasi Postman
  • Masukan terlebih dahulu authorization yang sebelumnya sudah dibuat
  • Dilanjut dengan mencoba method RESTnya yaitu POST,GET,DELETE
Test Membuat Data
Test Update Data
Test Read All
Read By
Delete Batch
Delete by

Referensi : 

membuat rest server sederhana dengan codeigniter 3 : https://www.codepolitan.com/rest-api-server-sederhana-dengan-codeigniter-58901f324a29f
mengatasi error pada library rest api terbaru : https://www.youtube.com/watch?v=cb3-Cm3Al3c&lc=UgyQpPjHXw8KcBurd2l4AaABAg

Download File Project
Terbaru
Postingan Lebih Baru
Terlama
Postingan Lama

Komentar