Cara Membuat Rest Api Codeigniter (CI)



Pertama download terlebih dahulu Codeigniter :

https://codeigniter.com/en/download

kemudian teman-teman konfig seperti biasanya dengan databasenya.

Setelah selesai di konfig silakan download libraries restApi CI di sini:

https://github.com/chriskacerguis/codeigniter-restserver

atau bisa juga menggunakan,

https://github.com/ardisaurus/ci-restserver (i used this)

setelah itu hal yang perlu di pindahkan yaitu,
  • config (folder) :  *rest.php
  • langunange (folder) : *english (folder)
  • libraries (folder) : *Format.php, *REST_Controller.php


Setelah itu buat controller untuk rest-Apinya seperti ini

<?php

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

require APPPATH . '/libraries/REST_Controller.php';
use Restserver\Libraries\REST_Controller;

class tesApi extends REST_Controller {

    function __construct($config = 'rest') {
        parent::__construct($config);
    }

    function index_get() {
        $id = $this->get('id');
        if ($id == '') {
            $kontak = $this->db->get('toko')->result();
        } else {
            $this->db->where('id', $id);
            $kontak = $this->db->get('profile')->result();
        }
        $this->response($kontak, 200);
    }

    function index_post() {
        $data = array(
                    'id'           => $this->post('id'),
                    'nama'          => $this->post('nama'),
                    'nomor'    => $this->post('nomor'));
        $insert = $this->db->insert('toko', $data);
        if ($insert) {
            $this->response($data, 200);
        } else {
            $this->response(array('status' => 'fail', 502));
        }
    }

    function index_put() {
        $id = $this->put('id');
        $data = array(
                    'id'       => $this->put('id'),
                    'nama'          => $this->put('nama'),
                    'nomor'    => $this->put('nomor'));
        $this->db->where('id', $id);
        $update = $this->db->update('toko', $data);
        if ($update) {
            $this->response($data, 200);
        } else {
            $this->response(array('status' => 'fail', 502));
        }
    }

    function index_delete() {
        $id = $this->delete('id');
        $this->db->where('id', $id);
        $delete = $this->db->delete('toko');
        if ($delete) {
            $this->response(array('status' => 'success'), 201);
        } else {
            $this->response(array('status' => 'fail', 502));
        }
    }

}
?>
kemudian test di web browser teman-teman atau POSTMAN 

http://127.0.0.1/rest_ci/index.php/tesApi

maka akan muncul seperti ini


saya menggunakan POSTMAN

Post a Comment

0 Comments