Create RESTful API with Code Igniter #1 : Basic installation, Setup configuration and Database, Create Routes API

in #utopian-io6 years ago (edited)

Repository

https://github.com/bcit-ci/CodeIgniter

What Will I Learn?

  • Basic installation
  • Setup configuration and database
  • How to make routes API

Requirements

  • Basic PHP
  • Install Ci > 3.1
  • Local server (Xampp, Wampp, or etc)
  • Mysqli

Resources

Difficulty

Basic

Tutorial Content

This time we will learn about one of the php frameworks that are quite popular and very powerful. That is code igniter (CI) . We will not learn from the basic, because there may be many tutorials that have discussed about it. in this tutorial we will learn how to create an API using this framework and we will also learn how to make authentication using the code igniter. Let's getting started..

Introduction

Because code igniter is a framework, the goal is to simplify and speed up programmers to create a project. to start this tutorial, you must install the code igniter first. in this tutorial I use code igniter 3.

  • Installing

Lets install it first, you can download here. After you have finished downloading you can run Code igniter on your localhost like Xammp, Wammp or etc. after you run it on your local server. we will see the results like the picture below, I put the code in the tutorial-ci folder.

Screenshot_2.png

If the image appears, that's means you have successfully installed it, then how can the page appear, let's find out.

  • Structure Code ignIter

What we see above comes from routes.php file, You can see the file directory as shown below.

Screenshot_3.png

routes.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

If we look at the code from routes.php, we will see $route['default_controller'] = 'welcome'; this means that if we don't enter any URL, the code igniter will call the default controller, in this code the default controller is 'welcome'.

Then we will go to the controller in the code igniter, we can see the contoller in the controllers folder, we can see as shown below.

Screenshot_4.png

Controller welcome.php

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

class Welcome extends CI_Controller {
    public function index()
    {
        $this->load->view('welcome_message');
    }
}
  • Then after the controller welcome is called in routes.php we will see the contents of the welcome controller, as we see in the picture above, in the welcome class class Welcome extends CI_Controller { }, there is anfunction index(){ } inside welcome controller. please note the index() is the default function that will automatically be called in the controller.

  • In the index function we call $this-> load-> view ('welcome_message');, This means we will call a view with the name welcome_message. We can see the view in the view folder, as shown below.

Screenshot_5.png

welcome_message.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Welcome to CodeIgniter</title>

    <style type="text/css">

    ::selection { background-color: #E13300; color: white; }
    ::-moz-selection { background-color: #E13300; color: white; }

    body {
        background-color: #fff;
        margin: 40px;
        font: 13px/20px normal Helvetica, Arial, sans-serif;
        color: #4F5155;
    }

    a {
        color: #003399;
        background-color: transparent;
        font-weight: normal;
    }

    h1 {
        color: #444;
        background-color: transparent;
        border-bottom: 1px solid #D0D0D0;
        font-size: 19px;
        font-weight: normal;
        margin: 0 0 14px 0;
        padding: 14px 15px 10px 15px;
    }

    code {
        font-family: Consolas, Monaco, Courier New, Courier, monospace;
        font-size: 12px;
        background-color: #f9f9f9;
        border: 1px solid #D0D0D0;
        color: #002166;
        display: block;
        margin: 14px 0 14px 0;
        padding: 12px 10px 12px 10px;
    }

    #body {
        margin: 0 15px 0 15px;
    }

    p.footer {
        text-align: right;
        font-size: 11px;
        border-top: 1px solid #D0D0D0;
        line-height: 32px;
        padding: 0 10px 0 10px;
        margin: 20px 0 0 0;
    }

    #container {
        margin: 10px;
        border: 1px solid #D0D0D0;
        box-shadow: 0 0 8px #D0D0D0;
    }
    </style>
</head>
<body>

<div id="container">
    <h1>Welcome to CodeIgniter!</h1>

    <div id="body">
        <p>The page you are looking at is being generated dynamically by CodeIgniter.</p>

        <p>If you would like to edit this page you'll find it located at:</p>
        <code>application/views/welcome_message.php</code>

        <p>The corresponding controller for this page is found at:</p>
        <code>application/controllers/Welcome.php</code>

        <p>If you are exploring CodeIgniter for the very first time, you should start by reading the <a href="user_guide/">User Guide</a>.</p>
    </div>

    <p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds. <?php echo  (ENVIRONMENT === 'development') ?  'CodeIgniter Version <strong>' . CI_VERSION . '</strong>' : '' ?></p>
</div>

</body>
</html>

Now we already know how the code igniter comes from and how to structure the folder, so we can conclude it is Routes -> Controller -> View. enough of our introduction with Code Igniter, because in this tutorial we will focus on creating an API. So I won't talk too much about the basics of the Code igniter, we will discuss it in other tutorials.

API Configuration

The first thing we will do configure on our application, we will do the settings in config.php, Because we will focus on the API we don't need the settings in the view or the frontend side.

Screenshot_6.png

The following is a snippet from the config.php file.

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

$config['base_url'] = 'http://localhost:80/tutorial_ci';
$config['index_page'] = ' ';
  • Create base url: We can make our own base_url specifically for API, so our endpoints will start from http://localhost:80/tutorial_ci/api.

  • Change root file: Because we will focus on the API we have to change our root, at the fresh download the Code Igniter our root application starts at index.php $config['index_page'] = ' index.php';. Now we will change it to $config['index_page'] = ' ';this means that our root starts from the application.

  • Create .htaccess: to remove index.php we need to create a .htaccess which is useful for redirecting the file or root after index.php index.php/$1.

.htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]


  • Add database library in autoload.php

Because we will only use the code igniter to make the API we only need to use the database library, we can set it on autoload.php like the example below

$autoload['libraries'] = array('database');

Database configuration

next, we will configure it in database.php.The following is the configuration of my database. adjust to your configuration. in this tutorial I use the mysqli driver database 'dbdriver' => 'mysqli'.

database.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'auth_ci',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

In this tutorial I use the 'database' => 'auth_ci', hostname 'hostname' => 'localhost' Username 'username' => 'root' Password 'password' => ' '.

  • Create Database

then we will create a database that we have configured in database.php, I will create an auth_ci database.

Screenshot_81.png

In this tutorial, I will create an API about authentication, so I will create table users. The following is the structure of the users table.

users.sql

CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL,
  `email` varchar(250) NOT NULL,
  `password` int(250) NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
NameTypeLength/ValueIndex
idint11Primary
emailvarchar250--
passwordvarchar250--
updated_attimestamp----
created_attimestamp----

Route API

We go back to routes.php, here we will start to make routing for our API. We will make a provision, all of our routing fires will have a fire prefix in the URL, this is commonly used in each endpoint. we can see an example like this

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

//Routes
$route['api/users']['GET']          = "UsersController/all_users"; // ENDPOINT to get all users data
$route['api/users/(:num)']['GET']   = "UsersController/detail_user/$1"; // ENDPOINT to detail user
$route['api/register']['POST']      = "UsersController/save"; // ENDPOINT to regsiter new user
$route['api/user/(:num)']['PUT']    = "UsersController/update/$1"; // ENDPOINT to edited/updated user
$route['api/user/(:num)']['DELETE'] = "UsersController/delete/$1"; // ENDPOINT to deleted user
$route['api/login']                 = "UsersController/save"; // ENDPOINT to Login


$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
  • Basic route: In the code igniter the way to write a route is quite easy, we just need to write down our route URL$route['api/users'] and then the method used ['GET'], after that we can initialize the controller we use and the method "UsersController/all_users";.

Example:

$route['URLendpoint']['METHOD'] = "Controllers/method";

  • Pass parameters on route: We can pass specific parameters on the route, because in this tutorial we will pass numbers, we can use (:num), to pass parameters that do not provide specific types you can use (:any). then we will accept these parameters in the controller in this way "UsersController/detail_user/$1";

Example:

$route['api/users/(:num)']['GET'] = "UsersController/detail_user/$1";

In routes.php we have made several types of methods and their uses, we have learned how to do the settings in the Code igniter to make it a RESTful API. In the next tutorial, we will start making the RESTful API for the authentication system. I hope this tutorial can explain you to start making RESTful API.

Proof of workdone

https://github.com/milleaduski/RESTful-CI

Sort:  

Thank you for your contribution @duski.harahap.
After reviewing your tutorial we suggest the following points:

  • We suggest you enter comments in your code. It is important for the reader to understand well the code that you put in your tutorial.

We really enjoyed the tutorial you developed. We are waiting for more of these tutorials.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thank you for your review, @portugalcoin!

So far this week you've reviewed 4 contributions. Keep up the good work!

Hi @duski.harahap!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Coin Marketplace

STEEM 0.33
TRX 0.11
JST 0.034
BTC 66363.68
ETH 3207.73
USDT 1.00
SBD 4.27