REST API Sederhana Menggunakan Codeigniter 3

REST API Sederhana Menggunakan Codeigniter 3

Sobatcoding.com - REST API Codeigniter 3

Setelah sebelumnya ada artikel tentang membuat REST API menggunakan Lumen Laravel, REST API Codeigniter 4, REST API Node Js, kali ini kita akan mencoba membuat REST API menggunakan Codeigiter 3. Sebagai contoh kita buat REST API crud user dan auth untuk login.

Sebetulnya ada sebuah library yang bisa dipakai untuk membuat REST API Codeigniter 3, yaitu CodeIgniter RestServer. Library ini dibuat oleh chriskacerguis, untuk download kalian bisa kunjungi di alamat github berikut chriskacerguis/codeigniter-restserver . Dengan library ini kalian bisa membuat Rest Server API secara mudah.

Kalian bisa juga download library ini via composer

composer require chriskacerguis/codeigniter-restserver

 

Namun kali ini kita akan mencoba membuat REST API sederhana menggunakan Codeigniter 3 sendiri tanpa menggunakan library tersebut.

Buatlah sebuah project baru menggunakan Codeigniter 3, misalkan restapi_ci3. Langkah selanjutnya kalian bisa ikuti langkah-langkah berikut.

 

Buat Tabel User

Buatlah sebuah tabel bernama m_users, kalian bisa import dari kode berikut.

DROP TABLE IF EXISTS `m_users`;
CREATE TABLE IF NOT EXISTS `m_users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(150) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `password` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `name` varchar(150) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `address` varchar(150) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `phone` varchar(150) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

//insert data
INSERT INTO `m_users` (`id`, `username`, `password`, `name`, `address`, `phone`, `created_at`, `updated_at`) VALUES (1, 'hadicahyono', '$2y$10$5dW9kw01Ue9cmkFaMzoZOebvXnVkiSuwjxHe1N.GFLtUCag9uKNem', 'Hadi Cahyono', 'Jl Majapahit No 55', '+62843643131313', '2021-09-29 11:50:05', '2022-04-26 21:48:14');
INSERT INTO `m_users` (`id`, `username`, `password`, `name`, `address`, `phone`, `created_at`, `updated_at`) VALUES (2, 'eninurdiana', 'eyJpdiI6Ik1Rdkt4b0x3TytWbUovVHlteHRiSVE9PSIsInZhbHVlIjoieFBsYTBzaTJlZndTN0xiZzY4SlhiZz09IiwibWFjIjoiMmEwMWY1MDI5YzQ0ZGRmYzVlYWRiZjcyMmEzYTYyYmU3NGZhMjhkZWM3ZmE5MWE4MTVlNTlmMWJkNzQxYWZlNyJ9', 'Eni Nurdiana S.', 'Jl Bunga Mawar No 121', '085762310001', '2021-09-29 12:06:01', '2021-09-29 12:06:02');
INSERT INTO `m_users` (`id`, `username`, `password`, `name`, `address`, `phone`, `created_at`, `updated_at`) VALUES (3, 'conor-klocko', '$2y$10$HgPN8lmAOA7A1A2v7Uri3egq/mEsYSKPGysutvLYjW5vGRwH/Maaa', 'Conor Klocko', NULL, '+12482238499', '2022-04-26 20:47:46', '2022-04-26 20:47:46');
INSERT INTO `m_users` (`id`, `username`, `password`, `name`, `address`, `phone`, `created_at`, `updated_at`) VALUES (4, 'theodora-pouros', '$2y$10$pgLQGy8NWmVhyzU2MJNySu6eQYqfYRmzoptcDiMZ2bcJRNC0zhJfu', 'Theodora Pouros', NULL, '+17543473687', '2022-04-26 20:47:46', '2022-04-26 20:47:46');
INSERT INTO `m_users` (`id`, `username`, `password`, `name`, `address`, `phone`, `created_at`, `updated_at`) VALUES (5, 'tanya-bogisich', '$2y$10$UOAQXbx7GSnCyZ2QkESVc.9wE0x2QtVH7sdUGE/nnBNNWOhTTLWo2', 'Tanya Bogisich', NULL, '+19382732920', '2022-04-26 20:47:46', '2022-04-26 20:47:46');
INSERT INTO `m_users` (`id`, `username`, `password`, `name`, `address`, `phone`, `created_at`, `updated_at`) VALUES (6, 'roberto-dach', '$2y$10$8qMAapaTtl1GcMzmo5DtE.UdO4OsV33noNjrzRegAAxrmb5LBhgCO', 'Roberto Dach', NULL, '+12566414085', '2022-04-26 20:47:46', '2022-04-26 20:47:46');
INSERT INTO `m_users` (`id`, `username`, `password`, `name`, `address`, `phone`, `created_at`, `updated_at`) VALUES (7, 'casandra-schmitt-phd', '$2y$10$DE.61NGlr20M4SRK2eX8f.E/KWCypA4m.WNjaLCmRST89KUEzOyrC', 'Casandra Schmitt PhD', NULL, '+17322259768', '2022-04-26 20:47:46', '2022-04-26 20:47:46');
INSERT INTO `m_users` (`id`, `username`, `password`, `name`, `address`, `phone`, `created_at`, `updated_at`) VALUES (8, 'prof-norval-howell-v', '$2y$10$6GGpvE/.L8IWfVQbqd9VketLTt0wO4IFToa6YflFewesKiDzSsEWq', 'Prof. Norval Howell V', NULL, '+18136487926', '2022-04-26 20:47:46', '2022-04-26 20:47:46');
INSERT INTO `m_users` (`id`, `username`, `password`, `name`, `address`, `phone`, `created_at`, `updated_at`) VALUES (9, 'anastacio-mccullough', '$2y$10$hf.pX3hfkCKoyXz7N2Jk/O8FUPzdRoR151st0x.v5h5omYSwgjuDi', 'Anastacio McCullough', NULL, '+12796630464', '2022-04-26 20:47:46', '2022-04-26 20:47:46');
INSERT INTO `m_users` (`id`, `username`, `password`, `name`, `address`, `phone`, `created_at`, `updated_at`) VALUES (10, 'ms-laila-fay-iii', '$2y$10$nqSqzaLEUlW22IQGFq9ABuPSrThi44HreWRpyBV2.OZxojhUxU2E.', 'Ms. Laila Fay III', NULL, '+16787683286', '2022-04-26 20:47:46', '2022-04-26 20:47:46');

Selanjutnya kalian bisa setting untuk config base_url dan database.

Buat Core

Buatlah sebuah core controller bernama REST_Controller.php dan siman di folder application/core.

class REST_Controller extends CI_Controller
{

    protected $_supported_formats = [
        'json' => 'application/json',
    ];

    public function __construct()
    {
        parent::__construct();
        $this->setCors();
    }

    protected function response($data, $status = 200)
    {
        http_response_code($status); //set response code
        $this->toJson($data);
        exit();
    }

    /**
     * Retreive POST INPUT
     */
    protected function getPost($input)
    {
        $content_type = $this->input->server('CONTENT_TYPE');
        $content_type = (strpos($content_type, ';') !== FALSE ? current(explode(';', $content_type)) : $content_type);
        //cek jika input content type adalah JSON
        if ($content_type == 'application/json') {
            $body = json_decode($this->input->raw_input_stream, true);
            return isset($body[$input]) ? $body[$input] : null;
        } else {
            return $this->input->post($input);
        }
    }

    /**
     * Retreive POST File
     */
    protected function getFile($input)
    {
        return isset($_FILES[$input]) ? $_FILES[$input] : null;
    }

    /**
     * Set Output to JSON
     */
    protected function toJson($data)
    {
        return $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($data, JSON_PRETTY_PRINT))->_display();

    }

    /**
     * Set CORS
     */
    private function setCors()
    {
        header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Max-Age: 86400"); //cache 1 day
        header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
    }

}

Di file config.php ubahlah line berikut.

/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries.  For more information please see the user guide:
|
| https://codeigniter.com/userguide3/general/core_classes.html
| https://codeigniter.com/userguide3/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'MY_'; //ubah line berikut

Ubah line di atas menjadi seperti berikut.

$config['subclass_prefix'] = 'REST_';

 

Buat Route

Buatlah route untuk CRUD user dan auth login

$route['users/delete/([0-9]+)']['GET'] = 'usersController/delete/$1';
$route['users/([0-9]+)']['POST'] = 'usersController/update/$1';
$route['users']['POST'] = 'usersController/save';
$route['users/([0-9]+)']['GET'] = 'usersController/show/$1';
$route['users']['GET'] = 'usersController/index';

$route['login']['POST'] = 'authController/login';

 

Buat Controller

Buatlah dua buah controller bernama AuthController.php dan UsersController.php. Kemudian masukkan kode seperti berikut untuk AuthController.php.

class AuthController extends REST_Controller {

    public function login()
    {
        //validation
        $error = [];
        if( !$this->getPost('username')) $error[] = 'Username harus diisi';
        if( !$this->getPost('password')) $error[] = 'Password harus diisi';

        if( count($error) > 0 )
        {
            $this->response(['success' => false, 'message' => $error[0] ], 422);
        }

        $exist = $this->db->get_where('m_users', ['username' => $this->getPost('username')])->row();
        if( $exist )
        {
            if( password_verify($this->getPost('password'), $exist->password) )
            {
                $data = $this->db->select('username, name, address, phone')->get_where('m_users',['id' => $exist->id])->row();
                $this->response( ['success'=> true, 'data' => $data]);
            }else{

			    $this->response( ['success'=> false, 'message' => 'User tidak ditemukan' ] );
		    }
        }else{
            $this->response( ['success'=> false, 'message' => 'User tidak ditemukan' ], 404 );
        }
    }

}

Untuk UsersController.php masukkan kode berikut.

class UsersController extends REST_Controller {

    public function index()
    {
        $data = $this->db->get('m_users')->result();
        $this->response(['success' => true, 'data' => $data]);
    }

    public function show($id)
    {
        $data = $this->db->get_where('m_users', ['id' => $id])->row();
        $this->response(['success' => true, 'data' => $data]);
    }

    public function save()
    {
        //validation
        $error = [];
        if( !$this->getPost('username')) $error[] = 'Username harus diisi';
        if( !$this->getPost('password')) $error[] = 'Password harus diisi';
        if( !$this->getPost('address')) $error[] = 'Alamat harus diisi';

        if( count($error) > 0 )
        {
            $this->response(['success' => false, 'message' => $error[0] ], 422);
        }

        $insert = [
            'username' => $this->getPost('username'),
            'password' => password_hash($this->getPost('password'), PASSWORD_DEFAULT),
            'address' => $this->getPost('address'),
            'phone' => $this->getPost('phone')
        ];
        $this->db->insert('m_users', $insert);

        $this->response(['success' => true, 'message' => 'Berhasil insert user']);
    }

    public function update($id)
    {
        $update = [];

        if( $this->getPost('password') ) $update['password'] = password_hash($this->getPost('password'), PASSWORD_DEFAULT);
        if( $this->getPost('address') ) $update['address'] = $this->getPost('address');
        if( $this->getPost('phone') ) $update['phone'] = $this->getPost('phone');
        
        $this->db->update('m_users', $update, ['id' => $id]);

        $this->response(['success' => true, 'message' => 'Berhasil update user']);
    }
    
    public function delete($id)
    {
        $this->db->where('id', $id);
        $this->db->delete('m_users');

        $this->response(['success' => true, 'message' => 'Berhasil delete user']);
    }

}

 

Testing API

Kalian bisa test menggunakan Postman

Test API Login

Login CI 3

Test API get user

API get user

Test API save user

API Post  User

 

Sekian tutorial kali ini. Jika teman-teman memiliki pertanyaan atau saran mengenai artikel ini, jangan ragu untuk meninggalkan komentar pada form di bawah ini.

Semoga bermanfaat.